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\Database\DBM;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Protocol\OStatus;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\XML;
24 use Text_LanguageDetect;
26 require_once 'boot.php';
27 require_once 'include/items.php';
28 require_once 'include/text.php';
30 class Item extends BaseObject
32 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
39 const PT_DOCUMENT = 19;
41 const PT_PERSONAL_NOTE = 128;
43 // Field list that is used to display the items
44 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
45 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
46 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
47 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
48 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
49 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
50 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
51 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
52 'writable', 'self', 'cid', 'alias',
53 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
54 'event-summary', 'event-desc', 'event-location', 'event-type',
55 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
57 // Field list that is used to deliver items via the protocols
58 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
59 'created', 'edited', 'verb', 'object-type', 'object', 'target',
60 'private', 'title', 'body', 'location', 'coord', 'app',
61 'attach', 'tag', 'deleted', 'extid', 'post-type',
62 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
63 'author-id', 'author-link', 'owner-link', 'contact-uid',
64 'signed_text', 'signature', 'signer', 'network'];
66 // Field list for "item-content" table that is mixed with the item table
67 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
68 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
69 'object-type', 'object', 'target-type', 'target', 'plink'];
71 // Field list for "item-content" table that is not present in the "item" table
72 const CONTENT_FIELDLIST = ['language'];
74 // Field list for additional delivery data
75 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
77 // All fields in the item table
78 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
79 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
80 'created', 'edited', 'commented', 'received', 'changed', 'verb',
81 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
82 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
83 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
84 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
85 'title', 'content-warning', 'body', 'location', 'coord', 'app',
86 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
87 'author-id', 'author-link', 'author-name', 'author-avatar',
88 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
90 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
91 // The item-activity table only stores the index and needs this array to know the matching activity.
92 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
94 private static $legacy_mode = null;
96 public static function isLegacyMode()
98 if (is_null(self::$legacy_mode)) {
99 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
102 return self::$legacy_mode;
106 * @brief returns an activity index from an activity string
108 * @param string $activity activity string
109 * @return integer Activity index
111 private static function activityToIndex($activity)
113 $index = array_search($activity, self::ACTIVITIES);
115 if (is_bool($index)) {
123 * @brief returns an activity string from an activity index
125 * @param integer $index activity index
126 * @return string Activity string
128 private static function indexToActivity($index)
130 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
134 return self::ACTIVITIES[$index];
138 * @brief Fetch a single item row
140 * @param mixed $stmt statement object
141 * @return array current row
143 public static function fetch($stmt)
145 $row = DBA::fetch($stmt);
151 // ---------------------- Transform item structure data ----------------------
153 // We prefer the data from the user's contact over the public one
154 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
155 ($row['author-link'] == $row['contact-link'])) {
156 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
157 $row['author-avatar'] = $row['contact-avatar'];
159 if (isset($row['author-name']) && !empty($row['contact-name'])) {
160 $row['author-name'] = $row['contact-name'];
164 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
165 ($row['owner-link'] == $row['contact-link'])) {
166 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
167 $row['owner-avatar'] = $row['contact-avatar'];
169 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
170 $row['owner-name'] = $row['contact-name'];
174 // We can always comment on posts from these networks
175 if (array_key_exists('writable', $row) &&
176 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
177 $row['writable'] = true;
180 // ---------------------- Transform item content data ----------------------
182 // Fetch data from the item-content table whenever there is content there
183 if (self::isLegacyMode()) {
184 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
185 foreach ($legacy_fields as $field) {
186 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
187 $row[$field] = $row['internal-item-' . $field];
189 unset($row['internal-item-' . $field]);
193 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
194 $row['verb'] = self::indexToActivity($row['internal-activity']);
195 if (array_key_exists('title', $row)) {
198 if (array_key_exists('body', $row)) {
199 $row['body'] = $row['verb'];
201 if (array_key_exists('object', $row)) {
204 if (array_key_exists('object-type', $row)) {
205 $row['object-type'] = ACTIVITY_OBJ_NOTE;
207 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
208 // Posts don't have an object or target - but having tags or files.
209 // We safe some performance by building tag and file strings only here.
210 // We remove object and target since they aren't used for this type.
211 if (array_key_exists('object', $row)) {
214 if (array_key_exists('target', $row)) {
219 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
220 // Build the tag string out of the term entries
221 if (array_key_exists('tag', $row) && empty($row['tag'])) {
222 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
225 // Build the file string out of the term entries
226 if (array_key_exists('file', $row) && empty($row['file'])) {
227 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
231 // Remove internal fields
232 unset($row['internal-activity']);
233 unset($row['internal-network']);
234 unset($row['internal-iid']);
235 unset($row['internal-iaid']);
236 unset($row['internal-icid']);
242 * @brief Fills an array with data from an item query
244 * @param object $stmt statement object
245 * @return array Data array
247 public static function inArray($stmt, $do_close = true) {
248 if (is_bool($stmt)) {
253 while ($row = self::fetch($stmt)) {
263 * @brief Check if item data exists
265 * @param array $condition array of fields for condition
267 * @return boolean Are there rows for that condition?
269 public static function exists($condition) {
270 $stmt = self::select(['id'], $condition, ['limit' => 1]);
272 if (is_bool($stmt)) {
275 $retval = (DBA::num_rows($stmt) > 0);
284 * Retrieve a single record from the item table for a given user and returns it in an associative array
286 * @brief Retrieve a single record from a table
287 * @param integer $uid User ID
288 * @param array $fields
289 * @param array $condition
290 * @param array $params
294 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
296 $params['uid'] = $uid;
298 if (empty($selected)) {
299 $selected = Item::DISPLAY_FIELDLIST;
302 return self::selectFirst($selected, $condition, $params);
306 * @brief Select rows from the item table for a given user
308 * @param integer $uid User ID
309 * @param array $selected Array of selected fields, empty for all
310 * @param array $condition Array of fields for condition
311 * @param array $params Array of several parameters
313 * @return boolean|object
315 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
317 $params['uid'] = $uid;
319 if (empty($selected)) {
320 $selected = Item::DISPLAY_FIELDLIST;
323 return self::select($selected, $condition, $params);
327 * Retrieve a single record from the item table and returns it in an associative array
329 * @brief Retrieve a single record from a table
330 * @param array $fields
331 * @param array $condition
332 * @param array $params
336 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
338 $params['limit'] = 1;
340 $result = self::select($fields, $condition, $params);
342 if (is_bool($result)) {
345 $row = self::fetch($result);
352 * @brief Select rows from the item table
354 * @param array $selected Array of selected fields, empty for all
355 * @param array $condition Array of fields for condition
356 * @param array $params Array of several parameters
358 * @return boolean|object
360 public static function select(array $selected = [], array $condition = [], $params = [])
365 if (isset($params['uid'])) {
366 $uid = $params['uid'];
370 $fields = self::fieldlist($selected);
372 $select_fields = self::constructSelectFields($fields, $selected);
374 $condition_string = DBA::buildCondition($condition);
376 $condition_string = self::addTablesToFields($condition_string, $fields);
379 $condition_string = $condition_string . ' AND ' . self::condition(false);
382 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
384 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
386 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
388 return DBA::p($sql, $condition);
392 * @brief Select rows from the starting post in the item table
394 * @param integer $uid User ID
395 * @param array $fields Array of selected fields, empty for all
396 * @param array $condition Array of fields for condition
397 * @param array $params Array of several parameters
399 * @return boolean|object
401 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
403 $params['uid'] = $uid;
405 if (empty($selected)) {
406 $selected = Item::DISPLAY_FIELDLIST;
409 return self::selectThread($selected, $condition, $params);
413 * Retrieve a single record from the starting post in the item table and returns it in an associative array
415 * @brief Retrieve a single record from a table
416 * @param integer $uid User ID
417 * @param array $selected
418 * @param array $condition
419 * @param array $params
423 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
425 $params['uid'] = $uid;
427 if (empty($selected)) {
428 $selected = Item::DISPLAY_FIELDLIST;
431 return self::selectFirstThread($selected, $condition, $params);
435 * Retrieve a single record from the starting post in the item table and returns it in an associative array
437 * @brief Retrieve a single record from a table
438 * @param array $fields
439 * @param array $condition
440 * @param array $params
444 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
446 $params['limit'] = 1;
447 $result = self::selectThread($fields, $condition, $params);
449 if (is_bool($result)) {
452 $row = self::fetch($result);
459 * @brief Select rows from the starting post in the item table
461 * @param array $selected Array of selected fields, empty for all
462 * @param array $condition Array of fields for condition
463 * @param array $params Array of several parameters
465 * @return boolean|object
467 public static function selectThread(array $selected = [], array $condition = [], $params = [])
472 if (isset($params['uid'])) {
473 $uid = $params['uid'];
477 $fields = self::fieldlist($selected);
479 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
480 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
481 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
482 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
484 $select_fields = self::constructSelectFields($fields, $selected);
486 $condition_string = DBA::buildCondition($condition);
488 $condition_string = self::addTablesToFields($condition_string, $threadfields);
489 $condition_string = self::addTablesToFields($condition_string, $fields);
492 $condition_string = $condition_string . ' AND ' . self::condition(true);
495 $param_string = DBA::buildParameter($params);
496 $param_string = self::addTablesToFields($param_string, $threadfields);
497 $param_string = self::addTablesToFields($param_string, $fields);
499 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
501 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
503 return DBA::p($sql, $condition);
507 * @brief Returns a list of fields that are associated with the item table
509 * @return array field list
511 private static function fieldlist($selected)
515 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
516 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
517 'created', 'edited', 'commented', 'received', 'changed',
518 'resource-id', 'event-id', 'tag', 'attach', 'post-type',
519 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid',
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['author'] = ['url' => 'author-link', 'name' => 'author-name',
533 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
535 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
536 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
538 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
539 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
540 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
542 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
544 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
546 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
547 'start' => 'event-start','finish' => 'event-finish',
548 'summary' => 'event-summary','desc' => 'event-desc',
549 'location' => 'event-location', 'type' => 'event-type',
550 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
551 'ignore' => 'event-ignore', 'id' => 'event-id'];
553 $fields['sign'] = ['signed_text', 'signature', 'signer'];
559 * @brief Returns SQL condition for the "select" functions
561 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
563 * @return string SQL condition
565 private static function condition($thread_mode)
568 $master_table = "`thread`";
570 $master_table = "`item`";
572 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`) ";
576 * @brief Returns all needed "JOIN" commands for the "select" functions
578 * @param integer $uid User ID
579 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
580 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
582 * @return string The SQL joins for the "select" functions
584 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
587 $master_table = "`thread`";
588 $master_table_key = "`thread`.`iid`";
589 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
591 $master_table = "`item`";
592 $master_table_key = "`item`.`id`";
597 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
598 AND NOT `contact`.`blocked`
599 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
600 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
601 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
602 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
603 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
604 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, GRAVITY_PARENT, intval($uid));
606 if (strpos($sql_commands, "`contact`.") !== false) {
607 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
609 if (strpos($sql_commands, "`author`.") !== false) {
610 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
612 if (strpos($sql_commands, "`owner`.") !== false) {
613 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
617 if (strpos($sql_commands, "`group_member`.") !== false) {
618 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
621 if (strpos($sql_commands, "`user`.") !== false) {
622 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
625 if (strpos($sql_commands, "`event`.") !== false) {
626 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
629 if (strpos($sql_commands, "`sign`.") !== false) {
630 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
633 if (strpos($sql_commands, "`item-activity`.") !== false) {
634 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
637 if (strpos($sql_commands, "`item-content`.") !== false) {
638 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
641 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
642 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
645 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
646 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
649 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
650 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
657 * @brief Add the field list for the "select" functions
659 * @param array $fields The field definition array
660 * @param array $selected The array with the selected fields from the "select" functions
662 * @return string The field list
664 private static function constructSelectFields($fields, $selected)
666 if (!empty($selected)) {
667 $selected[] = 'internal-iid';
668 $selected[] = 'internal-iaid';
669 $selected[] = 'internal-icid';
670 $selected[] = 'internal-network';
673 if (in_array('verb', $selected)) {
674 $selected[] = 'internal-activity';
678 foreach ($fields as $table => $table_fields) {
679 foreach ($table_fields as $field => $select) {
680 if (empty($selected) || in_array($select, $selected)) {
681 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
682 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
683 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
685 if (is_int($field)) {
686 $selection[] = "`" . $table . "`.`" . $select . "`";
688 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
693 return implode(", ", $selection);
697 * @brief add table definition to fields in an SQL query
699 * @param string $query SQL query
700 * @param array $fields The field definition array
702 * @return string the changed SQL query
704 private static function addTablesToFields($query, $fields)
706 foreach ($fields as $table => $table_fields) {
707 foreach ($table_fields as $alias => $field) {
708 if (is_int($alias)) {
709 $replace_field = $field;
711 $replace_field = $alias;
714 $search = "/([^\.])`" . $field . "`/i";
715 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
716 $query = preg_replace($search, $replace, $query);
723 * @brief Generate a server unique item hash for linking between the item tables
725 * @param string $uri Item URI
726 * @param date $created Item creation date
728 * @return string the item hash
730 private static function itemHash($uri, $created)
732 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
736 * @brief Update existing item entries
738 * @param array $fields The fields that are to be changed
739 * @param array $condition The condition for finding the item entries
741 * In the future we may have to change permissions as well.
742 * Then we had to add the user id as third parameter.
744 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
746 * @return integer|boolean number of affected rows - or "false" if there was an error
748 public static function update(array $fields, array $condition)
750 if (empty($condition) || empty($fields)) {
754 // To ensure the data integrity we do it in an transaction
757 // We cannot simply expand the condition to check for origin entries
758 // The condition needn't to be a simple array but could be a complex condition.
759 // And we have to execute this query before the update to ensure to fetch the same data.
760 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
762 $content_fields = [];
763 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
764 if (isset($fields[$field])) {
765 $content_fields[$field] = $fields[$field];
766 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
767 unset($fields[$field]);
769 $fields[$field] = null;
774 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
775 foreach ($clear_fields as $field) {
776 if (array_key_exists($field, $fields)) {
777 $fields[$field] = null;
781 if (array_key_exists('tag', $fields)) {
782 $tags = $fields['tag'];
783 $fields['tag'] = null;
788 if (array_key_exists('file', $fields)) {
789 $files = $fields['file'];
790 $fields['file'] = null;
795 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
796 'inform' => defaults($fields, 'inform', '')];
798 $fields['postopts'] = null;
799 $fields['inform'] = null;
801 if (!empty($fields)) {
802 $success = DBA::update('item', $fields, $condition);
811 // When there is no content for the "old" item table, this will count the fetched items
812 $rows = DBA::affected_rows();
814 while ($item = DBA::fetch($items)) {
816 // This part here can safely be removed when the legacy fields in the item had been removed
817 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
819 // Fetch the uri-hash from an existing item entry if there is one
820 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
821 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
822 if (DBM::is_result($existing)) {
823 $item['uri-hash'] = $existing['uri-hash'];
825 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
828 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
829 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
830 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
833 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
834 if (!empty($item['iaid'])) {
835 $update_condition = ['id' => $item['iaid']];
837 $update_condition = ['uri-hash' => $item['uri-hash']];
839 self::updateActivity($content_fields, $update_condition);
841 if (empty($item['iaid'])) {
842 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
843 if (DBM::is_result($item_activity)) {
844 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
845 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
846 if (self::isLegacyMode()) {
847 $item_fields[$field] = null;
849 unset($item_fields[$field]);
852 DBA::update('item', $item_fields, ['id' => $item['id']]);
854 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
855 DBA::delete('item-content', ['id' => $item['icid']]);
858 } elseif (!empty($item['icid'])) {
859 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
861 if (!DBA::exists('item', ['icid' => $item['icid']])) {
862 DBA::delete('item-content', ['id' => $item['icid']]);
866 if (!empty($item['icid'])) {
867 $update_condition = ['id' => $item['icid']];
869 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
871 self::updateContent($content_fields, $update_condition);
873 if (empty($item['icid'])) {
874 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
875 if (DBM::is_result($item_content)) {
876 $item_fields = ['icid' => $item_content['id']];
877 // Clear all fields in the item table that have a content in the item-content table
878 foreach ($item_content as $field => $content) {
879 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
880 if (self::isLegacyMode()) {
881 $item_fields[$field] = null;
883 unset($item_fields[$field]);
887 DBA::update('item', $item_fields, ['id' => $item['id']]);
893 Term::insertFromTagFieldByItemId($item['id'], $tags);
894 if (!empty($item['tag'])) {
895 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
899 if (!empty($files)) {
900 Term::insertFromFileFieldByItemId($item['id'], $files);
901 if (!empty($item['file'])) {
902 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
906 self::updateDeliveryData($item['id'], $delivery_data);
908 self::updateThread($item['id']);
910 // We only need to notfiy others when it is an original entry from us.
911 // Only call the notifier when the item has some content relevant change.
912 if ($item['origin'] && in_array('edited', array_keys($fields))) {
913 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
923 * @brief Delete an item and notify others about it - if it was ours
925 * @param array $condition The condition for finding the item entries
926 * @param integer $priority Priority for the notification
928 public static function delete($condition, $priority = PRIORITY_HIGH)
930 $items = DBA::select('item', ['id'], $condition);
931 while ($item = DBA::fetch($items)) {
932 self::deleteById($item['id'], $priority);
938 * @brief Delete an item for an user and notify others about it - if it was ours
940 * @param array $condition The condition for finding the item entries
941 * @param integer $uid User who wants to delete this item
943 public static function deleteForUser($condition, $uid)
949 $items = DBA::select('item', ['id', 'uid'], $condition);
950 while ($item = DBA::fetch($items)) {
951 // "Deleting" global items just means hiding them
952 if ($item['uid'] == 0) {
953 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
954 } elseif ($item['uid'] == $uid) {
955 self::deleteById($item['id'], PRIORITY_HIGH);
957 logger('Wrong ownership. Not deleting item ' . $item['id']);
964 * @brief Delete an item and notify others about it - if it was ours
966 * @param integer $item_id Item ID that should be delete
967 * @param integer $priority Priority for the notification
969 * @return boolean success
971 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
973 // locate item to be deleted
974 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
975 'deleted', 'file', 'resource-id', 'event-id', 'attach',
976 'verb', 'object-type', 'object', 'target', 'contact-id'];
977 $item = self::selectFirst($fields, ['id' => $item_id]);
978 if (!DBM::is_result($item)) {
979 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
983 if ($item['deleted']) {
984 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
988 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
989 if (!DBM::is_result($parent)) {
990 $parent = ['origin' => false];
993 // clean up categories and tags so they don't end up as orphans
996 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
998 foreach ($matches as $mtch) {
999 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1005 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1007 foreach ($matches as $mtch) {
1008 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1013 * If item is a link to a photo resource, nuke all the associated photos
1014 * (visitors will not have photo resources)
1015 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1016 * generate a resource-id and therefore aren't intimately linked to the item.
1018 if (strlen($item['resource-id'])) {
1019 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1022 // If item is a link to an event, delete the event.
1023 if (intval($item['event-id'])) {
1024 Event::delete($item['event-id']);
1027 // If item has attachments, drop them
1028 foreach (explode(", ", $item['attach']) as $attach) {
1029 preg_match("|attach/(\d+)|", $attach, $matches);
1030 if (is_array($matches) && count($matches) > 1) {
1031 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1035 // Delete tags that had been attached to other items
1036 self::deleteTagsFromItem($item);
1038 // Set the item to "deleted"
1039 // This erasing of item content is superfluous for items with a matching item-content.
1040 // But for the next time we will still have old content in the item table.
1041 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
1042 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
1043 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
1044 DBA::update('item', $item_fields, ['id' => $item['id']]);
1046 Term::insertFromTagFieldByItemId($item['id'], '');
1047 Term::insertFromFileFieldByItemId($item['id'], '');
1048 self::deleteThread($item['id'], $item['parent-uri']);
1050 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1051 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1054 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1056 // If it's the parent of a comment thread, kill all the kids
1057 if ($item['id'] == $item['parent']) {
1058 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1061 // Is it our comment and/or our thread?
1062 if ($item['origin'] || $parent['origin']) {
1064 // When we delete the original post we will delete all existing copies on the server as well
1065 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1067 // send the notification upstream/downstream
1068 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1069 } elseif ($item['uid'] != 0) {
1071 // When we delete just our local user copy of an item, we have to set a marker to hide it
1072 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1073 if (DBM::is_result($global_item)) {
1074 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1078 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1083 private static function deleteTagsFromItem($item)
1085 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1089 $xo = XML::parseString($item["object"], false);
1090 $xt = XML::parseString($item["target"], false);
1092 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1096 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1097 if (!DBM::is_result($i)) {
1101 // For tags, the owner cannot remove the tag on the author's copy of the post.
1102 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1103 $author_copy = $item["origin"];
1105 if (($owner_remove && $author_copy) || !$owner_remove) {
1109 $tags = explode(',', $i["tag"]);
1112 foreach ($tags as $tag) {
1113 if (trim($tag) !== trim($xo->body)) {
1114 $newtags[] = trim($tag);
1118 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1121 private static function guid($item, $notify)
1123 if (!empty($item['guid'])) {
1124 return notags(trim($item['guid']));
1128 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1129 // We add the hash of our own host because our host is the original creator of the post.
1130 $prefix_host = get_app()->get_hostname();
1134 // We are only storing the post so we create a GUID from the original hostname.
1135 if (!empty($item['author-link'])) {
1136 $parsed = parse_url($item['author-link']);
1137 if (!empty($parsed['host'])) {
1138 $prefix_host = $parsed['host'];
1142 if (empty($prefix_host) && !empty($item['plink'])) {
1143 $parsed = parse_url($item['plink']);
1144 if (!empty($parsed['host'])) {
1145 $prefix_host = $parsed['host'];
1149 if (empty($prefix_host) && !empty($item['uri'])) {
1150 $parsed = parse_url($item['uri']);
1151 if (!empty($parsed['host'])) {
1152 $prefix_host = $parsed['host'];
1156 // Is it in the format data@host.tld? - Used for mail contacts
1157 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1158 $mailparts = explode('@', $item['author-link']);
1159 $prefix_host = array_pop($mailparts);
1163 if (!empty($item['plink'])) {
1164 $guid = self::guidFromUri($item['plink'], $prefix_host);
1165 } elseif (!empty($item['uri'])) {
1166 $guid = self::guidFromUri($item['uri'], $prefix_host);
1168 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1174 private static function contactId($item)
1176 $contact_id = (int)$item["contact-id"];
1178 if (!empty($contact_id)) {
1181 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1183 * First we are looking for a suitable contact that matches with the author of the post
1184 * This is done only for comments
1186 if ($item['parent-uri'] != $item['uri']) {
1187 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1190 // If not present then maybe the owner was found
1191 if ($contact_id == 0) {
1192 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1195 // Still missing? Then use the "self" contact of the current user
1196 if ($contact_id == 0) {
1197 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1198 if (DBM::is_result($self)) {
1199 $contact_id = $self["id"];
1202 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1207 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1211 // If it is a posting where users should get notifications, then define it as wall posting
1214 $item['origin'] = 1;
1215 $item['network'] = NETWORK_DFRN;
1216 $item['protocol'] = PROTOCOL_DFRN;
1218 if (is_int($notify)) {
1219 $priority = $notify;
1221 $priority = PRIORITY_HIGH;
1224 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1227 $item['guid'] = self::guid($item, $notify);
1228 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1230 // Store conversation data
1231 $item = Conversation::insert($item);
1234 * If a Diaspora signature structure was passed in, pull it out of the
1235 * item array and set it aside for later storage.
1239 if (x($item, 'dsprsig')) {
1240 $encoded_signature = $item['dsprsig'];
1241 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1242 unset($item['dsprsig']);
1245 if (!empty($item['diaspora_signed_text'])) {
1246 $diaspora_signed_text = $item['diaspora_signed_text'];
1247 unset($item['diaspora_signed_text']);
1249 $diaspora_signed_text = '';
1252 // Converting the plink
1253 /// @TODO Check if this is really still needed
1254 if ($item['network'] == NETWORK_OSTATUS) {
1255 if (isset($item['plink'])) {
1256 $item['plink'] = OStatus::convertHref($item['plink']);
1257 } elseif (isset($item['uri'])) {
1258 $item['plink'] = OStatus::convertHref($item['uri']);
1262 if (!empty($item['thr-parent'])) {
1263 $item['parent-uri'] = $item['thr-parent'];
1266 if (isset($item['gravity'])) {
1267 $item['gravity'] = intval($item['gravity']);
1268 } elseif ($item['parent-uri'] === $item['uri']) {
1269 $item['gravity'] = GRAVITY_PARENT;
1270 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1271 $item['gravity'] = GRAVITY_COMMENT;
1273 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1274 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1277 $uid = intval($item['uid']);
1279 // check for create date and expire time
1280 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1282 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1283 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1284 $expire_interval = $user['expire'];
1287 if (($expire_interval > 0) && !empty($item['created'])) {
1288 $expire_date = time() - ($expire_interval * 86400);
1289 $created_date = strtotime($item['created']);
1290 if ($created_date < $expire_date) {
1291 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1297 * Do we already have this item?
1298 * We have to check several networks since Friendica posts could be repeated
1299 * via OStatus (maybe Diasporsa as well)
1301 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1302 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1303 trim($item['uri']), $item['uid'],
1304 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1305 $existing = self::selectFirst(['id', 'network'], $condition);
1306 if (DBM::is_result($existing)) {
1307 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1309 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1312 return $existing["id"];
1316 // Ensure to always have the same creation date.
1317 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1318 if (DBM::is_result($existing)) {
1319 $item['created'] = $existing['created'];
1320 $item['uri-hash'] = $existing['uri-hash'];
1323 self::addLanguageToItemArray($item);
1325 $item['wall'] = intval(defaults($item, 'wall', 0));
1326 $item['extid'] = trim(defaults($item, 'extid', ''));
1327 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1328 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1329 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1330 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1331 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1332 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1333 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1334 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1335 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1336 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1337 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1338 $item['title'] = trim(defaults($item, 'title', ''));
1339 $item['location'] = trim(defaults($item, 'location', ''));
1340 $item['coord'] = trim(defaults($item, 'coord', ''));
1341 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1342 $item['deleted'] = 0;
1343 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1344 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1345 $item['verb'] = trim(defaults($item, 'verb', ''));
1346 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1347 $item['object'] = trim(defaults($item, 'object', ''));
1348 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1349 $item['target'] = trim(defaults($item, 'target', ''));
1350 $item['plink'] = trim(defaults($item, 'plink', ''));
1351 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1352 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1353 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1354 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1355 $item['private'] = intval(defaults($item, 'private', 0));
1356 $item['body'] = trim(defaults($item, 'body', ''));
1357 $item['tag'] = trim(defaults($item, 'tag', ''));
1358 $item['attach'] = trim(defaults($item, 'attach', ''));
1359 $item['app'] = trim(defaults($item, 'app', ''));
1360 $item['origin'] = intval(defaults($item, 'origin', 0));
1361 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1362 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1363 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1364 $item['inform'] = trim(defaults($item, 'inform', ''));
1365 $item['file'] = trim(defaults($item, 'file', ''));
1367 // Unique identifier to be linked against item-activities and item-content
1368 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1370 // When there is no content then we don't post it
1371 if ($item['body'].$item['title'] == '') {
1372 logger('No body, no title.');
1376 // Items cannot be stored before they happen ...
1377 if ($item['created'] > DateTimeFormat::utcNow()) {
1378 $item['created'] = DateTimeFormat::utcNow();
1381 // We haven't invented time travel by now.
1382 if ($item['edited'] > DateTimeFormat::utcNow()) {
1383 $item['edited'] = DateTimeFormat::utcNow();
1386 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1388 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1389 $item["contact-id"] = self::contactId($item);
1391 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1392 'photo' => $item['author-avatar'], 'network' => $item['network']];
1394 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1396 if (Contact::isBlocked($item["author-id"])) {
1397 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1401 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1402 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1404 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1406 if (Contact::isBlocked($item["owner-id"])) {
1407 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1411 // These fields aren't stored anymore in the item table, they are fetched upon request
1412 unset($item['author-link']);
1413 unset($item['author-name']);
1414 unset($item['author-avatar']);
1416 unset($item['owner-link']);
1417 unset($item['owner-name']);
1418 unset($item['owner-avatar']);
1420 if ($item['network'] == NETWORK_PHANTOM) {
1421 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1423 $item['network'] = NETWORK_DFRN;
1424 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1427 // Checking if there is already an item with the same guid
1428 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1429 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1430 if (self::exists($condition)) {
1431 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1435 // Check for hashtags in the body and repair or add hashtag links
1436 self::setHashtags($item);
1438 $item['thr-parent'] = $item['parent-uri'];
1446 if ($item['parent-uri'] === $item['uri']) {
1448 $parent_deleted = 0;
1449 $allow_cid = $item['allow_cid'];
1450 $allow_gid = $item['allow_gid'];
1451 $deny_cid = $item['deny_cid'];
1452 $deny_gid = $item['deny_gid'];
1453 $notify_type = 'wall-new';
1455 // find the parent and snarf the item id and ACLs
1456 // and anything else we need to inherit
1458 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1459 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1460 'wall', 'private', 'forum_mode', 'origin'];
1461 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1462 $params = ['order' => ['id' => false]];
1463 $parent = self::selectFirst($fields, $condition, $params);
1465 if (DBM::is_result($parent)) {
1466 // is the new message multi-level threaded?
1467 // even though we don't support it now, preserve the info
1468 // and re-attach to the conversation parent.
1470 if ($parent['uri'] != $parent['parent-uri']) {
1471 $item['parent-uri'] = $parent['parent-uri'];
1473 $condition = ['uri' => $item['parent-uri'],
1474 'parent-uri' => $item['parent-uri'],
1475 'uid' => $item['uid']];
1476 $params = ['order' => ['id' => false]];
1477 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1479 if (DBM::is_result($toplevel_parent)) {
1480 $parent = $toplevel_parent;
1484 $parent_id = $parent['id'];
1485 $parent_deleted = $parent['deleted'];
1486 $allow_cid = $parent['allow_cid'];
1487 $allow_gid = $parent['allow_gid'];
1488 $deny_cid = $parent['deny_cid'];
1489 $deny_gid = $parent['deny_gid'];
1490 $item['wall'] = $parent['wall'];
1491 $notify_type = 'comment-new';
1494 * If the parent is private, force privacy for the entire conversation
1495 * This differs from the above settings as it subtly allows comments from
1496 * email correspondents to be private even if the overall thread is not.
1498 if ($parent['private']) {
1499 $item['private'] = $parent['private'];
1503 * Edge case. We host a public forum that was originally posted to privately.
1504 * The original author commented, but as this is a comment, the permissions
1505 * weren't fixed up so it will still show the comment as private unless we fix it here.
1507 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1508 $item['private'] = 0;
1511 // If its a post from myself then tag the thread as "mention"
1512 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1513 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1514 if (DBM::is_result($user)) {
1515 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1516 $self_id = Contact::getIdForURL($self, 0, true);
1517 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1518 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1519 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1520 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1525 * Allow one to see reply tweets from status.net even when
1526 * we don't have or can't see the original post.
1528 if ($force_parent) {
1529 logger('$force_parent=true, reply converted to top-level post.');
1531 $item['parent-uri'] = $item['uri'];
1532 $item['gravity'] = GRAVITY_PARENT;
1534 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1538 $parent_deleted = 0;
1542 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1543 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1544 if (self::exists($condition)) {
1545 logger('duplicated item with the same uri found. '.print_r($item,true));
1549 // On Friendica and Diaspora the GUID is unique
1550 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1551 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1552 if (self::exists($condition)) {
1553 logger('duplicated item with the same guid found. '.print_r($item,true));
1557 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1558 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1559 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1560 if (self::exists($condition)) {
1561 logger('duplicated item with the same body found. '.print_r($item,true));
1566 // Is this item available in the global items (with uid=0)?
1567 if ($item["uid"] == 0) {
1568 $item["global"] = true;
1570 // Set the global flag on all items if this was a global item entry
1571 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1573 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1577 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1580 $private = $item['private'];
1583 $item["allow_cid"] = $allow_cid;
1584 $item["allow_gid"] = $allow_gid;
1585 $item["deny_cid"] = $deny_cid;
1586 $item["deny_gid"] = $deny_gid;
1587 $item["private"] = $private;
1588 $item["deleted"] = $parent_deleted;
1590 // Fill the cache field
1591 put_item_in_cache($item);
1594 $item['edit'] = false;
1595 $item['parent'] = $parent_id;
1596 Addon::callHooks('post_local', $item);
1597 unset($item['edit']);
1598 unset($item['parent']);
1600 Addon::callHooks('post_remote', $item);
1603 // This array field is used to trigger some automatic reactions
1604 // It is mainly used in the "post_local" hook.
1605 unset($item['api_source']);
1607 if (x($item, 'cancel')) {
1608 logger('post cancelled by addon.');
1613 * Check for already added items.
1614 * There is a timing issue here that sometimes creates double postings.
1615 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1617 if ($item["uid"] == 0) {
1618 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1619 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1624 logger('' . print_r($item,true), LOGGER_DATA);
1626 if (array_key_exists('tag', $item)) {
1627 $tags = $item['tag'];
1628 unset($item['tag']);
1633 if (array_key_exists('file', $item)) {
1634 $files = $item['file'];
1635 unset($item['file']);
1640 // Creates the permission set
1641 // Currently we only store the data but don't using it
1642 $item['psid'] = PermissionSet::fetchIDForPost($item);
1644 // We are doing this outside of the transaction to avoid timing problems
1645 if (!self::insertActivity($item)) {
1646 self::insertContent($item);
1649 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1650 'inform' => defaults($item, 'inform', '')];
1652 unset($item['postopts']);
1653 unset($item['inform']);
1656 $ret = DBA::insert('item', $item);
1658 // When the item was successfully stored we fetch the ID of the item.
1659 if (DBM::is_result($ret)) {
1660 $current_post = DBA::lastInsertId();
1662 // This can happen - for example - if there are locking timeouts.
1665 // Store the data into a spool file so that we can try again later.
1667 // At first we restore the Diaspora signature that we removed above.
1668 if (isset($encoded_signature)) {
1669 $item['dsprsig'] = $encoded_signature;
1672 // Now we store the data in the spool directory
1673 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1674 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1676 $spoolpath = get_spoolpath();
1677 if ($spoolpath != "") {
1678 $spool = $spoolpath.'/'.$file;
1680 // Ensure to have the removed data from above again in the item array
1681 $item = array_merge($item, $delivery_data);
1683 file_put_contents($spool, json_encode($item));
1684 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1689 if ($current_post == 0) {
1690 // This is one of these error messages that never should occur.
1691 logger("couldn't find created item - we better quit now.");
1696 // How much entries have we created?
1697 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1698 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1701 // There are duplicates. We delete our just created entry.
1702 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1704 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1705 DBA::delete('item', ['id' => $current_post]);
1708 } elseif ($entries == 0) {
1709 // This really should never happen since we quit earlier if there were problems.
1710 logger("Something is terribly wrong. We haven't found our created entry.");
1715 logger('created item '.$current_post);
1716 self::updateContact($item);
1718 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1719 $parent_id = $current_post;
1723 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1725 $item['id'] = $current_post;
1726 $item['parent'] = $parent_id;
1728 // update the commented timestamp on the parent
1729 // Only update "commented" if it is really a comment
1730 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1731 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1733 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1738 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1739 * We can check for this condition when we decode and encode the stuff again.
1741 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1742 $dsprsig->signature = base64_decode($dsprsig->signature);
1743 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1746 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1747 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1750 if (!empty($diaspora_signed_text)) {
1751 // Formerly we stored the signed text, the signature and the author in different fields.
1752 // We now store the raw data so that we are more flexible.
1753 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1756 $deleted = self::tagDeliver($item['uid'], $current_post);
1759 * current post can be deleted if is for a community page and no mention are
1762 if (!$deleted && !$dontcache) {
1763 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1764 if (DBM::is_result($posted_item)) {
1766 Addon::callHooks('post_local_end', $posted_item);
1768 Addon::callHooks('post_remote_end', $posted_item);
1771 logger('new item not found in DB, id ' . $current_post);
1775 if ($item['parent-uri'] === $item['uri']) {
1776 self::addThread($current_post);
1778 self::updateThread($parent_id);
1781 $delivery_data['iid'] = $current_post;
1783 self::insertDeliveryData($delivery_data);
1788 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1789 * This is not perfect - but a workable solution until we found the reason for the problem.
1791 if (!empty($tags)) {
1792 Term::insertFromTagFieldByItemId($current_post, $tags);
1795 if (!empty($files)) {
1796 Term::insertFromFileFieldByItemId($current_post, $files);
1799 if ($item['parent-uri'] === $item['uri']) {
1800 self::addShadow($current_post);
1802 self::addShadowPost($current_post);
1805 check_user_notification($current_post);
1808 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1809 } elseif (!empty($parent) && $parent['origin']) {
1810 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1813 return $current_post;
1817 * @brief Insert a new item delivery data entry
1819 * @param array $item The item fields that are to be inserted
1821 private static function insertDeliveryData($delivery_data)
1823 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1827 DBA::insert('item-delivery-data', $delivery_data);
1831 * @brief Update an existing item delivery data entry
1833 * @param integer $id The item id that is to be updated
1834 * @param array $item The item fields that are to be inserted
1836 private static function updateDeliveryData($id, $delivery_data)
1838 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1842 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1846 * @brief Insert a new item content entry
1848 * @param array $item The item fields that are to be inserted
1850 private static function insertActivity(&$item)
1852 $activity_index = self::activityToIndex($item['verb']);
1854 if ($activity_index < 0) {
1858 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1859 'uri-hash' => $item['uri-hash']];
1861 // We just remove everything that is content
1862 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1863 unset($item[$field]);
1866 // To avoid timing problems, we are using locks.
1867 $locked = Lock::acquire('item_insert_activity');
1869 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1872 // Do we already have this content?
1873 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1874 if (DBM::is_result($item_activity)) {
1875 $item['iaid'] = $item_activity['id'];
1876 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1877 } elseif (DBA::insert('item-activity', $fields)) {
1878 $item['iaid'] = DBA::lastInsertId();
1879 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1881 // This shouldn't happen.
1882 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1886 Lock::release('item_insert_activity');
1892 * @brief Insert a new item content entry
1894 * @param array $item The item fields that are to be inserted
1896 private static function insertContent(&$item)
1898 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1900 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1901 if (isset($item[$field])) {
1902 $fields[$field] = $item[$field];
1903 unset($item[$field]);
1907 // To avoid timing problems, we are using locks.
1908 $locked = Lock::acquire('item_insert_content');
1910 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1913 // Do we already have this content?
1914 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1915 if (DBM::is_result($item_content)) {
1916 $item['icid'] = $item_content['id'];
1917 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1918 } elseif (DBA::insert('item-content', $fields)) {
1919 $item['icid'] = DBA::lastInsertId();
1920 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1922 // This shouldn't happen.
1923 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1926 Lock::release('item_insert_content');
1931 * @brief Update existing item content entries
1933 * @param array $item The item fields that are to be changed
1934 * @param array $condition The condition for finding the item content entries
1936 private static function updateActivity($item, $condition)
1938 if (empty($item['verb'])) {
1941 $activity_index = self::activityToIndex($item['verb']);
1943 if ($activity_index < 0) {
1947 $fields = ['activity' => $activity_index];
1949 logger('Update activity for ' . json_encode($condition));
1951 DBA::update('item-activity', $fields, $condition, true);
1957 * @brief Update existing item content entries
1959 * @param array $item The item fields that are to be changed
1960 * @param array $condition The condition for finding the item content entries
1962 private static function updateContent($item, $condition)
1964 // We have to select only the fields from the "item-content" table
1966 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1967 if (isset($item[$field])) {
1968 $fields[$field] = $item[$field];
1972 if (empty($fields)) {
1973 // when there are no fields at all, just use the condition
1974 // This is to ensure that we always store content.
1975 $fields = $condition;
1978 logger('Update content for ' . json_encode($condition));
1980 DBA::update('item-content', $fields, $condition, true);
1984 * @brief Distributes public items to the receivers
1986 * @param integer $itemid Item ID that should be added
1987 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1989 public static function distribute($itemid, $signed_text = '')
1991 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1992 $parent = self::selectFirst(['owner-id'], $condition);
1993 if (!DBM::is_result($parent)) {
1997 // Only distribute public items from native networks
1998 $condition = ['id' => $itemid, 'uid' => 0,
1999 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2000 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2001 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2002 if (!DBM::is_result($item)) {
2006 $origin = $item['origin'];
2009 unset($item['parent']);
2010 unset($item['mention']);
2011 unset($item['wall']);
2012 unset($item['origin']);
2013 unset($item['starred']);
2017 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2018 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
2019 $contacts = DBA::select('contact', ['uid'], $condition);
2020 while ($contact = DBA::fetch($contacts)) {
2021 $users[$contact['uid']] = $contact['uid'];
2026 if ($item['uri'] != $item['parent-uri']) {
2027 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2028 while ($parent = DBA::fetch($parents)) {
2029 $users[$parent['uid']] = $parent['uid'];
2030 if ($parent['origin'] && !$origin) {
2031 $origin_uid = $parent['uid'];
2036 foreach ($users as $uid) {
2037 if ($origin_uid == $uid) {
2038 $item['diaspora_signed_text'] = $signed_text;
2040 self::storeForUser($itemid, $item, $uid);
2045 * @brief Store public items for the receivers
2047 * @param integer $itemid Item ID that should be added
2048 * @param array $item The item entry that will be stored
2049 * @param integer $uid The user that will receive the item entry
2051 private static function storeForUser($itemid, $item, $uid)
2053 $item['uid'] = $uid;
2054 $item['origin'] = 0;
2056 if ($item['uri'] == $item['parent-uri']) {
2057 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2059 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2062 if (empty($item['contact-id'])) {
2063 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2064 if (!DBM::is_result($self)) {
2067 $item['contact-id'] = $self['id'];
2070 /// @todo Handling of "event-id"
2073 if ($item['uri'] == $item['parent-uri']) {
2074 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2075 if (DBM::is_result($contact)) {
2076 $notify = self::isRemoteSelf($contact, $item);
2080 $distributed = self::insert($item, false, $notify, true);
2082 if (!$distributed) {
2083 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2085 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2090 * @brief Add a shadow entry for a given item id that is a thread starter
2092 * We store every public item entry additionally with the user id "0".
2093 * This is used for the community page and for the search.
2094 * It is planned that in the future we will store public item entries only once.
2096 * @param integer $itemid Item ID that should be added
2098 public static function addShadow($itemid)
2100 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2101 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2102 $item = self::selectFirst($fields, $condition);
2104 if (!DBM::is_result($item)) {
2108 // is it already a copy?
2109 if (($itemid == 0) || ($item['uid'] == 0)) {
2113 // Is it a visible public post?
2114 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2118 // is it an entry from a connector? Only add an entry for natively connected networks
2119 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2123 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2127 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2129 if (DBM::is_result($item)) {
2130 // Preparing public shadow (removing user specific data)
2133 unset($item['parent']);
2134 unset($item['wall']);
2135 unset($item['mention']);
2136 unset($item['origin']);
2137 unset($item['starred']);
2138 unset($item['postopts']);
2139 unset($item['inform']);
2140 if ($item['uri'] == $item['parent-uri']) {
2141 $item['contact-id'] = $item['owner-id'];
2143 $item['contact-id'] = $item['author-id'];
2146 $public_shadow = self::insert($item, false, false, true);
2148 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2153 * @brief Add a shadow entry for a given item id that is a comment
2155 * This function does the same like the function above - but for comments
2157 * @param integer $itemid Item ID that should be added
2159 public static function addShadowPost($itemid)
2161 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2162 if (!DBM::is_result($item)) {
2166 // Is it a toplevel post?
2167 if ($item['id'] == $item['parent']) {
2168 self::addShadow($itemid);
2172 // Is this a shadow entry?
2173 if ($item['uid'] == 0) {
2177 // Is there a shadow parent?
2178 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2182 // Is there already a shadow entry?
2183 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2187 // Save "origin" and "parent" state
2188 $origin = $item['origin'];
2189 $parent = $item['parent'];
2191 // Preparing public shadow (removing user specific data)
2194 unset($item['parent']);
2195 unset($item['wall']);
2196 unset($item['mention']);
2197 unset($item['origin']);
2198 unset($item['starred']);
2199 unset($item['postopts']);
2200 unset($item['inform']);
2201 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2203 $public_shadow = self::insert($item, false, false, true);
2205 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2207 // If this was a comment to a Diaspora post we don't get our comment back.
2208 // This means that we have to distribute the comment by ourselves.
2209 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2210 self::distribute($public_shadow);
2215 * Adds a language specification in a "language" element of given $arr.
2216 * Expects "body" element to exist in $arr.
2218 private static function addLanguageToItemArray(&$item)
2220 $naked_body = BBCode::toPlaintext($item['body'], false);
2222 $ld = new Text_LanguageDetect();
2223 $ld->setNameMode(2);
2224 $languages = $ld->detect($naked_body, 3);
2226 if (is_array($languages)) {
2227 $item['language'] = json_encode($languages);
2232 * @brief Creates an unique guid out of a given uri
2234 * @param string $uri uri of an item entry
2235 * @param string $host hostname for the GUID prefix
2236 * @return string unique guid
2238 public static function guidFromUri($uri, $host)
2240 // Our regular guid routine is using this kind of prefix as well
2241 // We have to avoid that different routines could accidentally create the same value
2242 $parsed = parse_url($uri);
2244 // We use a hash of the hostname as prefix for the guid
2245 $guid_prefix = hash("crc32", $host);
2247 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2248 unset($parsed["scheme"]);
2250 // Glue it together to be able to make a hash from it
2251 $host_id = implode("/", $parsed);
2253 // We could use any hash algorithm since it isn't a security issue
2254 $host_hash = hash("ripemd128", $host_id);
2256 return $guid_prefix.$host_hash;
2260 * generate an unique URI
2262 * @param integer $uid User id
2263 * @param string $guid An existing GUID (Otherwise it will be generated)
2267 public static function newURI($uid, $guid = "")
2270 $guid = System::createGUID(32);
2273 $hostname = self::getApp()->get_hostname();
2275 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2277 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2283 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2285 * This can be used to filter for inactive contacts.
2286 * Only do this for public postings to avoid privacy problems, since poco data is public.
2287 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2289 * @param array $arr Contains the just posted item record
2291 private static function updateContact($arr)
2293 // Unarchive the author
2294 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2295 if (DBM::is_result($contact)) {
2296 Contact::unmarkForArchival($contact);
2299 // Unarchive the contact if it's not our own contact
2300 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2301 if (DBM::is_result($contact)) {
2302 Contact::unmarkForArchival($contact);
2305 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2307 // Is it a forum? Then we don't care about the rules from above
2308 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2309 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2315 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2316 ['id' => $arr['contact-id']]);
2318 // Now do the same for the system wide contacts with uid=0
2319 if (!$arr['private']) {
2320 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2321 ['id' => $arr['owner-id']]);
2323 if ($arr['owner-id'] != $arr['author-id']) {
2324 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2325 ['id' => $arr['author-id']]);
2330 public static function setHashtags(&$item)
2333 $tags = get_tags($item["body"]);
2336 if (!count($tags)) {
2340 // This sorting is important when there are hashtags that are part of other hashtags
2341 // Otherwise there could be problems with hashtags like #test and #test2
2344 $URLSearchString = "^\[\]";
2346 // All hashtags should point to the home server if "local_tags" is activated
2347 if (Config::get('system', 'local_tags')) {
2348 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2349 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2351 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2352 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2355 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2356 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2358 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2361 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2363 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2366 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2368 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2371 // Repair recursive urls
2372 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2373 "#$2", $item["body"]);
2375 foreach ($tags as $tag) {
2376 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2380 $basetag = str_replace('_',' ',substr($tag,1));
2382 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2384 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2386 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2387 if (strlen($item["tag"])) {
2388 $item["tag"] = ','.$item["tag"];
2390 $item["tag"] = $newtag.$item["tag"];
2394 // Convert back the masked hashtags
2395 $item["body"] = str_replace("#", "#", $item["body"]);
2398 public static function getGuidById($id)
2400 $item = self::selectFirst(['guid'], ['id' => $id]);
2401 if (DBM::is_result($item)) {
2402 return $item['guid'];
2408 public static function getIdAndNickByGuid($guid, $uid = 0)
2414 $uid == local_user();
2417 // Does the given user have this item?
2419 $item = DBA::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2420 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2421 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2422 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2423 if (DBM::is_result($item)) {
2425 $nick = $item["nickname"];
2429 // Or is it anywhere on the server?
2431 $item = DBA::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2432 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2433 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2434 AND NOT `item`.`private` AND `item`.`wall`
2435 AND `item`.`guid` = ?", $guid);
2436 if (DBM::is_result($item)) {
2438 $nick = $item["nickname"];
2441 return ["nick" => $nick, "id" => $id];
2445 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2447 * @param int $item_id
2448 * @return bool true if item was deleted, else false
2450 private static function tagDeliver($uid, $item_id)
2454 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2455 if (!DBM::is_result($user)) {
2459 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2460 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2462 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2463 if (!DBM::is_result($item)) {
2467 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2470 * Diaspora uses their own hardwired link URL in @-tags
2471 * instead of the one we supply with webfinger
2473 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2475 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2477 foreach ($matches as $mtch) {
2478 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2480 logger('mention found: ' . $mtch[2]);
2486 if (($community_page || $prvgroup) &&
2487 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2488 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2490 logger("no-mention top-level post to community or private group. delete.");
2491 DBA::delete('item', ['id' => $item_id]);
2497 $arr = ['item' => $item, 'user' => $user];
2499 Addon::callHooks('tagged', $arr);
2501 if (!$community_page && !$prvgroup) {
2506 * tgroup delivery - setup a second delivery chain
2507 * prevent delivery looping - only proceed
2508 * if the message originated elsewhere and is a top-level post
2510 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2514 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2515 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2516 if (!DBM::is_result($self)) {
2520 $owner_id = Contact::getIdForURL($self['url']);
2522 // also reset all the privacy bits to the forum default permissions
2524 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2526 $forum_mode = ($prvgroup ? 2 : 1);
2528 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2529 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2530 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2531 DBA::update('item', $fields, ['id' => $item_id]);
2533 self::updateThread($item_id);
2535 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2538 public static function isRemoteSelf($contact, &$datarray)
2542 if (!$contact['remote_self']) {
2546 // Prevent the forwarding of posts that are forwarded
2547 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2548 logger('Already forwarded', LOGGER_DEBUG);
2552 // Prevent to forward already forwarded posts
2553 if ($datarray["app"] == $a->get_hostname()) {
2554 logger('Already forwarded (second test)', LOGGER_DEBUG);
2558 // Only forward posts
2559 if ($datarray["verb"] != ACTIVITY_POST) {
2560 logger('No post', LOGGER_DEBUG);
2564 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2565 logger('Not public', LOGGER_DEBUG);
2569 $datarray2 = $datarray;
2570 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2571 if ($contact['remote_self'] == 2) {
2572 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2573 ['uid' => $contact['uid'], 'self' => true]);
2574 if (DBM::is_result($self)) {
2575 $datarray['contact-id'] = $self["id"];
2577 $datarray['owner-name'] = $self["name"];
2578 $datarray['owner-link'] = $self["url"];
2579 $datarray['owner-avatar'] = $self["thumb"];
2581 $datarray['author-name'] = $datarray['owner-name'];
2582 $datarray['author-link'] = $datarray['owner-link'];
2583 $datarray['author-avatar'] = $datarray['owner-avatar'];
2585 unset($datarray['created']);
2586 unset($datarray['edited']);
2588 unset($datarray['network']);
2589 unset($datarray['owner-id']);
2590 unset($datarray['author-id']);
2593 if ($contact['network'] != NETWORK_FEED) {
2594 $datarray["guid"] = System::createGUID(32);
2595 unset($datarray["plink"]);
2596 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2597 $datarray["parent-uri"] = $datarray["uri"];
2598 $datarray["thr-parent"] = $datarray["uri"];
2599 $datarray["extid"] = NETWORK_DFRN;
2600 $urlpart = parse_url($datarray2['author-link']);
2601 $datarray["app"] = $urlpart["host"];
2603 $datarray['private'] = 0;
2607 if ($contact['network'] != NETWORK_FEED) {
2608 // Store the original post
2609 $result = self::insert($datarray2, false, false);
2610 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2612 $datarray["app"] = "Feed";
2616 // Trigger automatic reactions for addons
2617 $datarray['api_source'] = true;
2619 // We have to tell the hooks who we are - this really should be improved
2620 $_SESSION["authenticated"] = true;
2621 $_SESSION["uid"] = $contact['uid'];
2630 * @param array $item
2634 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2636 if (Config::get('system', 'disable_embedded')) {
2640 logger('check for photos', LOGGER_DEBUG);
2641 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2646 $img_start = strpos($orig_body, '[img');
2647 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2648 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2650 while (($img_st_close !== false) && ($img_len !== false)) {
2651 $img_st_close++; // make it point to AFTER the closing bracket
2652 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2654 logger('found photo ' . $image, LOGGER_DEBUG);
2656 if (stristr($image, $site . '/photo/')) {
2657 // Only embed locally hosted photos
2659 $i = basename($image);
2660 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2661 $x = strpos($i, '-');
2664 $res = substr($i, $x + 1);
2665 $i = substr($i, 0, $x);
2666 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2667 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2668 if (DBM::is_result($photo)) {
2670 * Check to see if we should replace this photo link with an embedded image
2671 * 1. No need to do so if the photo is public
2672 * 2. If there's a contact-id provided, see if they're in the access list
2673 * for the photo. If so, embed it.
2674 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2675 * permissions, regardless of order but first check to see if they're an exact
2676 * match to save some processing overhead.
2678 if (self::hasPermissions($photo)) {
2680 $recips = self::enumeratePermissions($photo);
2681 if (in_array($cid, $recips)) {
2685 if (self::samePermissions($item, $photo)) {
2691 $data = $photo['data'];
2692 $type = $photo['type'];
2694 // If a custom width and height were specified, apply before embedding
2695 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2696 logger('scaling photo', LOGGER_DEBUG);
2698 $width = intval($match[1]);
2699 $height = intval($match[2]);
2701 $Image = new Image($data, $type);
2702 if ($Image->isValid()) {
2703 $Image->scaleDown(max($width, $height));
2704 $data = $Image->asString();
2705 $type = $Image->getType();
2709 logger('replacing photo', LOGGER_DEBUG);
2710 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2711 logger('replaced: ' . $image, LOGGER_DATA);
2717 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2718 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2719 if ($orig_body === false) {
2723 $img_start = strpos($orig_body, '[img');
2724 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2725 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2728 $new_body = $new_body . $orig_body;
2733 private static function hasPermissions($obj)
2735 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2736 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2739 private static function samePermissions($obj1, $obj2)
2741 // first part is easy. Check that these are exactly the same.
2742 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2743 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2744 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2745 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2749 // This is harder. Parse all the permissions and compare the resulting set.
2750 $recipients1 = self::enumeratePermissions($obj1);
2751 $recipients2 = self::enumeratePermissions($obj2);
2755 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2756 return ($recipients1 == $recipients2);
2759 // returns an array of contact-ids that are allowed to see this object
2760 private static function enumeratePermissions($obj)
2762 $allow_people = expand_acl($obj['allow_cid']);
2763 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2764 $deny_people = expand_acl($obj['deny_cid']);
2765 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2766 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2767 $deny = array_unique(array_merge($deny_people, $deny_groups));
2768 $recipients = array_diff($recipients, $deny);
2772 public static function getFeedTags($item)
2776 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2778 for ($x = 0; $x < $cnt; $x ++) {
2779 if ($matches[1][$x]) {
2780 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2785 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2787 for ($x = 0; $x < $cnt; $x ++) {
2788 if ($matches[1][$x]) {
2789 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2796 public static function expire($uid, $days, $network = "", $force = false)
2798 if (!$uid || ($days < 1)) {
2802 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2803 $uid, GRAVITY_PARENT];
2806 * $expire_network_only = save your own wall posts
2807 * and just expire conversations started by others
2809 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2811 if ($expire_network_only) {
2812 $condition[0] .= " AND NOT `wall`";
2815 if ($network != "") {
2816 $condition[0] .= " AND `network` = ?";
2817 $condition[] = $network;
2820 * There is an index "uid_network_received" but not "uid_network_created"
2821 * This avoids the creation of another index just for one purpose.
2822 * And it doesn't really matter wether to look at "received" or "created"
2824 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2825 $condition[] = $days;
2827 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2828 $condition[] = $days;
2831 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2833 if (!DBM::is_result($items)) {
2837 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2839 // Forcing expiring of items - but not notes and marked items
2841 $expire_items = true;
2844 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2845 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2846 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2850 while ($item = Item::fetch($items)) {
2851 // don't expire filed items
2853 if (strpos($item['file'], '[') !== false) {
2857 // Only expire posts, not photos and photo comments
2859 if (!$expire_photos && strlen($item['resource-id'])) {
2861 } elseif (!$expire_starred && intval($item['starred'])) {
2863 } elseif (!$expire_notes && $item['type'] == 'note') {
2865 } elseif (!$expire_items && $item['type'] != 'note') {
2869 self::deleteById($item['id'], PRIORITY_LOW);
2874 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2877 public static function firstPostDate($uid, $wall = false)
2879 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2880 $params = ['order' => ['created' => false]];
2881 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2882 if (DBM::is_result($thread)) {
2883 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2889 * @brief add/remove activity to an item
2891 * Toggle activities as like,dislike,attend of an item
2893 * @param string $item_id
2894 * @param string $verb
2895 * Activity verb. One of
2896 * like, unlike, dislike, undislike, attendyes, unattendyes,
2897 * attendno, unattendno, attendmaybe, unattendmaybe
2898 * @hook 'post_local_end'
2900 * 'post_id' => ID of posted item
2902 public static function performLike($item_id, $verb)
2904 if (!local_user() && !remote_user()) {
2911 $activity = ACTIVITY_LIKE;
2915 $activity = ACTIVITY_DISLIKE;
2919 $activity = ACTIVITY_ATTEND;
2923 $activity = ACTIVITY_ATTENDNO;
2926 case 'unattendmaybe':
2927 $activity = ACTIVITY_ATTENDMAYBE;
2930 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2934 // Enable activity toggling instead of on/off
2935 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2937 logger('like: verb ' . $verb . ' item ' . $item_id);
2939 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2940 if (!DBM::is_result($item)) {
2941 logger('like: unknown item ' . $item_id);
2945 $item_uri = $item['uri'];
2947 $uid = $item['uid'];
2948 if (($uid == 0) && local_user()) {
2949 $uid = local_user();
2952 if (!can_write_wall($uid)) {
2953 logger('like: unable to write on wall ' . $uid);
2957 // Retrieves the local post owner
2958 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2959 if (!DBM::is_result($owner_self_contact)) {
2960 logger('like: unknown owner ' . $uid);
2964 // Retrieve the current logged in user's public contact
2965 $author_id = public_contact();
2967 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
2968 if (!DBM::is_result($author_contact)) {
2969 logger('like: unknown author ' . $author_id);
2973 // Contact-id is the uid-dependant author contact
2974 if (local_user() == $uid) {
2975 $item_contact_id = $owner_self_contact['id'];
2976 $item_contact = $owner_self_contact;
2978 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2979 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
2980 if (!DBM::is_result($item_contact)) {
2981 logger('like: unknown item contact ' . $item_contact_id);
2986 // Look for an existing verb row
2987 // event participation are essentially radio toggles. If you make a subsequent choice,
2988 // we need to eradicate your first choice.
2989 if ($event_verb_flag) {
2990 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2992 // Translate to the index based activity index
2994 foreach ($verbs as $verb) {
2995 $activities[] = self::activityToIndex($verb);
2998 $activities = self::activityToIndex($activity);
3001 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3002 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3004 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3006 // If it exists, mark it as deleted
3007 if (DBM::is_result($like_item)) {
3008 // Already voted, undo it
3009 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
3010 /// @todo Consider using self::update - but before doing so, check the side effects
3011 DBA::update('item', $fields, ['id' => $like_item['id']]);
3013 // Clean up the Diaspora signatures for this like
3014 DBA::delete('sign', ['iid' => $like_item['id']]);
3016 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
3018 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3023 // Verb is "un-something", just trying to delete existing entries
3024 if (strpos($verb, 'un') === 0) {
3028 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3031 'guid' => System::createGUID(32),
3032 'uri' => self::newURI($item['uid']),
3033 'uid' => $item['uid'],
3034 'contact-id' => $item_contact_id,
3035 'wall' => $item['wall'],
3037 'network' => NETWORK_DFRN,
3038 'gravity' => GRAVITY_ACTIVITY,
3039 'parent' => $item['id'],
3040 'parent-uri' => $item['uri'],
3041 'thr-parent' => $item['uri'],
3042 'owner-id' => $item['owner-id'],
3043 'author-id' => $author_id,
3044 'body' => $activity,
3045 'verb' => $activity,
3046 'object-type' => $objtype,
3047 'allow_cid' => $item['allow_cid'],
3048 'allow_gid' => $item['allow_gid'],
3049 'deny_cid' => $item['deny_cid'],
3050 'deny_gid' => $item['deny_gid'],
3055 $new_item_id = self::insert($new_item);
3057 // If the parent item isn't visible then set it to visible
3058 if (!$item['visible']) {
3059 self::update(['visible' => true], ['id' => $item['id']]);
3062 // Save the author information for the like in case we need to relay to Diaspora
3063 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3065 $new_item['id'] = $new_item_id;
3067 Addon::callHooks('post_local_end', $new_item);
3069 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3074 private static function addThread($itemid, $onlyshadow = false)
3076 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3077 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3078 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3079 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3080 $item = self::selectFirst($fields, $condition);
3082 if (!DBM::is_result($item)) {
3086 $item['iid'] = $itemid;
3089 $result = DBA::insert('thread', $item);
3091 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3095 private static function updateThread($itemid, $setmention = false)
3097 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3098 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3099 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3100 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3102 $item = self::selectFirst($fields, $condition);
3103 if (!DBM::is_result($item)) {
3108 $item["mention"] = 1;
3115 foreach ($item as $field => $data) {
3116 if (!in_array($field, ["guid"])) {
3117 $fields[$field] = $data;
3121 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3123 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3126 private static function deleteThread($itemid, $itemuri = "")
3128 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3129 if (!DBM::is_result($item)) {
3130 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3134 // Using dba::delete at this time could delete the associated item entries
3135 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3137 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3139 if ($itemuri != "") {
3140 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3141 if (!self::exists($condition)) {
3142 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3143 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);