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::affectedRows();
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 // This function will finally cover most of the preparation functionality in mod/item.php
1208 public static function prepare(&$item)
1210 $data = BBCode::getAttachmentData($item['body']);
1211 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1212 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1213 $posttype = Item::PT_PAGE;
1214 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1218 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1222 // If it is a posting where users should get notifications, then define it as wall posting
1225 $item['origin'] = 1;
1226 $item['network'] = NETWORK_DFRN;
1227 $item['protocol'] = PROTOCOL_DFRN;
1229 if (is_int($notify)) {
1230 $priority = $notify;
1232 $priority = PRIORITY_HIGH;
1235 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1238 $item['guid'] = self::guid($item, $notify);
1239 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1241 // Store conversation data
1242 $item = Conversation::insert($item);
1245 * If a Diaspora signature structure was passed in, pull it out of the
1246 * item array and set it aside for later storage.
1250 if (x($item, 'dsprsig')) {
1251 $encoded_signature = $item['dsprsig'];
1252 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1253 unset($item['dsprsig']);
1256 if (!empty($item['diaspora_signed_text'])) {
1257 $diaspora_signed_text = $item['diaspora_signed_text'];
1258 unset($item['diaspora_signed_text']);
1260 $diaspora_signed_text = '';
1263 // Converting the plink
1264 /// @TODO Check if this is really still needed
1265 if ($item['network'] == NETWORK_OSTATUS) {
1266 if (isset($item['plink'])) {
1267 $item['plink'] = OStatus::convertHref($item['plink']);
1268 } elseif (isset($item['uri'])) {
1269 $item['plink'] = OStatus::convertHref($item['uri']);
1273 if (!empty($item['thr-parent'])) {
1274 $item['parent-uri'] = $item['thr-parent'];
1277 if (isset($item['gravity'])) {
1278 $item['gravity'] = intval($item['gravity']);
1279 } elseif ($item['parent-uri'] === $item['uri']) {
1280 $item['gravity'] = GRAVITY_PARENT;
1281 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1282 $item['gravity'] = GRAVITY_COMMENT;
1284 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1285 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1288 $uid = intval($item['uid']);
1290 // check for create date and expire time
1291 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1293 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1294 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1295 $expire_interval = $user['expire'];
1298 if (($expire_interval > 0) && !empty($item['created'])) {
1299 $expire_date = time() - ($expire_interval * 86400);
1300 $created_date = strtotime($item['created']);
1301 if ($created_date < $expire_date) {
1302 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1308 * Do we already have this item?
1309 * We have to check several networks since Friendica posts could be repeated
1310 * via OStatus (maybe Diasporsa as well)
1312 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1313 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1314 trim($item['uri']), $item['uid'],
1315 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1316 $existing = self::selectFirst(['id', 'network'], $condition);
1317 if (DBM::is_result($existing)) {
1318 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1320 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1323 return $existing["id"];
1327 // Ensure to always have the same creation date.
1328 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1329 if (DBM::is_result($existing)) {
1330 $item['created'] = $existing['created'];
1331 $item['uri-hash'] = $existing['uri-hash'];
1334 self::addLanguageToItemArray($item);
1336 $item['wall'] = intval(defaults($item, 'wall', 0));
1337 $item['extid'] = trim(defaults($item, 'extid', ''));
1338 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1339 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1340 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1341 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1342 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1343 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1344 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1345 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1346 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1347 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1348 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1349 $item['title'] = trim(defaults($item, 'title', ''));
1350 $item['location'] = trim(defaults($item, 'location', ''));
1351 $item['coord'] = trim(defaults($item, 'coord', ''));
1352 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1353 $item['deleted'] = 0;
1354 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1355 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1356 $item['verb'] = trim(defaults($item, 'verb', ''));
1357 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1358 $item['object'] = trim(defaults($item, 'object', ''));
1359 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1360 $item['target'] = trim(defaults($item, 'target', ''));
1361 $item['plink'] = trim(defaults($item, 'plink', ''));
1362 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1363 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1364 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1365 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1366 $item['private'] = intval(defaults($item, 'private', 0));
1367 $item['body'] = trim(defaults($item, 'body', ''));
1368 $item['tag'] = trim(defaults($item, 'tag', ''));
1369 $item['attach'] = trim(defaults($item, 'attach', ''));
1370 $item['app'] = trim(defaults($item, 'app', ''));
1371 $item['origin'] = intval(defaults($item, 'origin', 0));
1372 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1373 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1374 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1375 $item['inform'] = trim(defaults($item, 'inform', ''));
1376 $item['file'] = trim(defaults($item, 'file', ''));
1378 // Unique identifier to be linked against item-activities and item-content
1379 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1381 // When there is no content then we don't post it
1382 if ($item['body'].$item['title'] == '') {
1383 logger('No body, no title.');
1387 // Items cannot be stored before they happen ...
1388 if ($item['created'] > DateTimeFormat::utcNow()) {
1389 $item['created'] = DateTimeFormat::utcNow();
1392 // We haven't invented time travel by now.
1393 if ($item['edited'] > DateTimeFormat::utcNow()) {
1394 $item['edited'] = DateTimeFormat::utcNow();
1397 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1399 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1400 $item["contact-id"] = self::contactId($item);
1402 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1403 'photo' => $item['author-avatar'], 'network' => $item['network']];
1405 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1407 if (Contact::isBlocked($item["author-id"])) {
1408 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1412 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1413 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1415 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1417 if (Contact::isBlocked($item["owner-id"])) {
1418 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1422 // These fields aren't stored anymore in the item table, they are fetched upon request
1423 unset($item['author-link']);
1424 unset($item['author-name']);
1425 unset($item['author-avatar']);
1427 unset($item['owner-link']);
1428 unset($item['owner-name']);
1429 unset($item['owner-avatar']);
1431 if ($item['network'] == NETWORK_PHANTOM) {
1432 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1434 $item['network'] = NETWORK_DFRN;
1435 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1438 // Checking if there is already an item with the same guid
1439 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1440 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1441 if (self::exists($condition)) {
1442 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1446 // Check for hashtags in the body and repair or add hashtag links
1447 self::setHashtags($item);
1449 $item['thr-parent'] = $item['parent-uri'];
1457 if ($item['parent-uri'] === $item['uri']) {
1459 $parent_deleted = 0;
1460 $allow_cid = $item['allow_cid'];
1461 $allow_gid = $item['allow_gid'];
1462 $deny_cid = $item['deny_cid'];
1463 $deny_gid = $item['deny_gid'];
1464 $notify_type = 'wall-new';
1466 // find the parent and snarf the item id and ACLs
1467 // and anything else we need to inherit
1469 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1470 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1471 'wall', 'private', 'forum_mode', 'origin'];
1472 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1473 $params = ['order' => ['id' => false]];
1474 $parent = self::selectFirst($fields, $condition, $params);
1476 if (DBM::is_result($parent)) {
1477 // is the new message multi-level threaded?
1478 // even though we don't support it now, preserve the info
1479 // and re-attach to the conversation parent.
1481 if ($parent['uri'] != $parent['parent-uri']) {
1482 $item['parent-uri'] = $parent['parent-uri'];
1484 $condition = ['uri' => $item['parent-uri'],
1485 'parent-uri' => $item['parent-uri'],
1486 'uid' => $item['uid']];
1487 $params = ['order' => ['id' => false]];
1488 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1490 if (DBM::is_result($toplevel_parent)) {
1491 $parent = $toplevel_parent;
1495 $parent_id = $parent['id'];
1496 $parent_deleted = $parent['deleted'];
1497 $allow_cid = $parent['allow_cid'];
1498 $allow_gid = $parent['allow_gid'];
1499 $deny_cid = $parent['deny_cid'];
1500 $deny_gid = $parent['deny_gid'];
1501 $item['wall'] = $parent['wall'];
1502 $notify_type = 'comment-new';
1505 * If the parent is private, force privacy for the entire conversation
1506 * This differs from the above settings as it subtly allows comments from
1507 * email correspondents to be private even if the overall thread is not.
1509 if ($parent['private']) {
1510 $item['private'] = $parent['private'];
1514 * Edge case. We host a public forum that was originally posted to privately.
1515 * The original author commented, but as this is a comment, the permissions
1516 * weren't fixed up so it will still show the comment as private unless we fix it here.
1518 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1519 $item['private'] = 0;
1522 // If its a post from myself then tag the thread as "mention"
1523 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1524 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1525 if (DBM::is_result($user)) {
1526 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1527 $self_id = Contact::getIdForURL($self, 0, true);
1528 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1529 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1530 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1531 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1536 * Allow one to see reply tweets from status.net even when
1537 * we don't have or can't see the original post.
1539 if ($force_parent) {
1540 logger('$force_parent=true, reply converted to top-level post.');
1542 $item['parent-uri'] = $item['uri'];
1543 $item['gravity'] = GRAVITY_PARENT;
1545 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1549 $parent_deleted = 0;
1553 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1554 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1555 if (self::exists($condition)) {
1556 logger('duplicated item with the same uri found. '.print_r($item,true));
1560 // On Friendica and Diaspora the GUID is unique
1561 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1562 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1563 if (self::exists($condition)) {
1564 logger('duplicated item with the same guid found. '.print_r($item,true));
1568 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1569 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1570 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1571 if (self::exists($condition)) {
1572 logger('duplicated item with the same body found. '.print_r($item,true));
1577 // Is this item available in the global items (with uid=0)?
1578 if ($item["uid"] == 0) {
1579 $item["global"] = true;
1581 // Set the global flag on all items if this was a global item entry
1582 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1584 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1588 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1591 $private = $item['private'];
1594 $item["allow_cid"] = $allow_cid;
1595 $item["allow_gid"] = $allow_gid;
1596 $item["deny_cid"] = $deny_cid;
1597 $item["deny_gid"] = $deny_gid;
1598 $item["private"] = $private;
1599 $item["deleted"] = $parent_deleted;
1601 // Fill the cache field
1602 put_item_in_cache($item);
1605 $item['edit'] = false;
1606 $item['parent'] = $parent_id;
1607 Addon::callHooks('post_local', $item);
1608 unset($item['edit']);
1609 unset($item['parent']);
1611 Addon::callHooks('post_remote', $item);
1614 // This array field is used to trigger some automatic reactions
1615 // It is mainly used in the "post_local" hook.
1616 unset($item['api_source']);
1618 if (x($item, 'cancel')) {
1619 logger('post cancelled by addon.');
1624 * Check for already added items.
1625 * There is a timing issue here that sometimes creates double postings.
1626 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1628 if ($item["uid"] == 0) {
1629 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1630 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1635 logger('' . print_r($item,true), LOGGER_DATA);
1637 if (array_key_exists('tag', $item)) {
1638 $tags = $item['tag'];
1639 unset($item['tag']);
1644 if (array_key_exists('file', $item)) {
1645 $files = $item['file'];
1646 unset($item['file']);
1651 // Creates the permission set
1652 // Currently we only store the data but don't using it
1653 $item['psid'] = PermissionSet::fetchIDForPost($item);
1655 // We are doing this outside of the transaction to avoid timing problems
1656 if (!self::insertActivity($item)) {
1657 self::insertContent($item);
1660 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1661 'inform' => defaults($item, 'inform', '')];
1663 unset($item['postopts']);
1664 unset($item['inform']);
1667 $ret = DBA::insert('item', $item);
1669 // When the item was successfully stored we fetch the ID of the item.
1670 if (DBM::is_result($ret)) {
1671 $current_post = DBA::lastInsertId();
1673 // This can happen - for example - if there are locking timeouts.
1676 // Store the data into a spool file so that we can try again later.
1678 // At first we restore the Diaspora signature that we removed above.
1679 if (isset($encoded_signature)) {
1680 $item['dsprsig'] = $encoded_signature;
1683 // Now we store the data in the spool directory
1684 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1685 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1687 $spoolpath = get_spoolpath();
1688 if ($spoolpath != "") {
1689 $spool = $spoolpath.'/'.$file;
1691 // Ensure to have the removed data from above again in the item array
1692 $item = array_merge($item, $delivery_data);
1694 file_put_contents($spool, json_encode($item));
1695 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1700 if ($current_post == 0) {
1701 // This is one of these error messages that never should occur.
1702 logger("couldn't find created item - we better quit now.");
1707 // How much entries have we created?
1708 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1709 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1712 // There are duplicates. We delete our just created entry.
1713 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1715 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1716 DBA::delete('item', ['id' => $current_post]);
1719 } elseif ($entries == 0) {
1720 // This really should never happen since we quit earlier if there were problems.
1721 logger("Something is terribly wrong. We haven't found our created entry.");
1726 logger('created item '.$current_post);
1727 self::updateContact($item);
1729 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1730 $parent_id = $current_post;
1734 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1736 $item['id'] = $current_post;
1737 $item['parent'] = $parent_id;
1739 // update the commented timestamp on the parent
1740 // Only update "commented" if it is really a comment
1741 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1742 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1744 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1749 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1750 * We can check for this condition when we decode and encode the stuff again.
1752 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1753 $dsprsig->signature = base64_decode($dsprsig->signature);
1754 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1757 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1758 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1761 if (!empty($diaspora_signed_text)) {
1762 // Formerly we stored the signed text, the signature and the author in different fields.
1763 // We now store the raw data so that we are more flexible.
1764 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1767 $deleted = self::tagDeliver($item['uid'], $current_post);
1770 * current post can be deleted if is for a community page and no mention are
1773 if (!$deleted && !$dontcache) {
1774 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1775 if (DBM::is_result($posted_item)) {
1777 Addon::callHooks('post_local_end', $posted_item);
1779 Addon::callHooks('post_remote_end', $posted_item);
1782 logger('new item not found in DB, id ' . $current_post);
1786 if ($item['parent-uri'] === $item['uri']) {
1787 self::addThread($current_post);
1789 self::updateThread($parent_id);
1792 $delivery_data['iid'] = $current_post;
1794 self::insertDeliveryData($delivery_data);
1799 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1800 * This is not perfect - but a workable solution until we found the reason for the problem.
1802 if (!empty($tags)) {
1803 Term::insertFromTagFieldByItemId($current_post, $tags);
1806 if (!empty($files)) {
1807 Term::insertFromFileFieldByItemId($current_post, $files);
1810 if ($item['parent-uri'] === $item['uri']) {
1811 self::addShadow($current_post);
1813 self::addShadowPost($current_post);
1816 check_user_notification($current_post);
1819 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1820 } elseif (!empty($parent) && $parent['origin']) {
1821 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1824 return $current_post;
1828 * @brief Insert a new item delivery data entry
1830 * @param array $item The item fields that are to be inserted
1832 private static function insertDeliveryData($delivery_data)
1834 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1838 DBA::insert('item-delivery-data', $delivery_data);
1842 * @brief Update an existing item delivery data entry
1844 * @param integer $id The item id that is to be updated
1845 * @param array $item The item fields that are to be inserted
1847 private static function updateDeliveryData($id, $delivery_data)
1849 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1853 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1857 * @brief Insert a new item content entry
1859 * @param array $item The item fields that are to be inserted
1861 private static function insertActivity(&$item)
1863 $activity_index = self::activityToIndex($item['verb']);
1865 if ($activity_index < 0) {
1869 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1870 'uri-hash' => $item['uri-hash']];
1872 // We just remove everything that is content
1873 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1874 unset($item[$field]);
1877 // To avoid timing problems, we are using locks.
1878 $locked = Lock::acquire('item_insert_activity');
1880 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1883 // Do we already have this content?
1884 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1885 if (DBM::is_result($item_activity)) {
1886 $item['iaid'] = $item_activity['id'];
1887 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1888 } elseif (DBA::insert('item-activity', $fields)) {
1889 $item['iaid'] = DBA::lastInsertId();
1890 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1892 // This shouldn't happen.
1893 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1897 Lock::release('item_insert_activity');
1903 * @brief Insert a new item content entry
1905 * @param array $item The item fields that are to be inserted
1907 private static function insertContent(&$item)
1909 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1911 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1912 if (isset($item[$field])) {
1913 $fields[$field] = $item[$field];
1914 unset($item[$field]);
1918 // To avoid timing problems, we are using locks.
1919 $locked = Lock::acquire('item_insert_content');
1921 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1924 // Do we already have this content?
1925 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1926 if (DBM::is_result($item_content)) {
1927 $item['icid'] = $item_content['id'];
1928 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1929 } elseif (DBA::insert('item-content', $fields)) {
1930 $item['icid'] = DBA::lastInsertId();
1931 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1933 // This shouldn't happen.
1934 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1937 Lock::release('item_insert_content');
1942 * @brief Update existing item content entries
1944 * @param array $item The item fields that are to be changed
1945 * @param array $condition The condition for finding the item content entries
1947 private static function updateActivity($item, $condition)
1949 if (empty($item['verb'])) {
1952 $activity_index = self::activityToIndex($item['verb']);
1954 if ($activity_index < 0) {
1958 $fields = ['activity' => $activity_index];
1960 logger('Update activity for ' . json_encode($condition));
1962 DBA::update('item-activity', $fields, $condition, true);
1968 * @brief Update existing item content entries
1970 * @param array $item The item fields that are to be changed
1971 * @param array $condition The condition for finding the item content entries
1973 private static function updateContent($item, $condition)
1975 // We have to select only the fields from the "item-content" table
1977 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1978 if (isset($item[$field])) {
1979 $fields[$field] = $item[$field];
1983 if (empty($fields)) {
1984 // when there are no fields at all, just use the condition
1985 // This is to ensure that we always store content.
1986 $fields = $condition;
1989 logger('Update content for ' . json_encode($condition));
1991 DBA::update('item-content', $fields, $condition, true);
1995 * @brief Distributes public items to the receivers
1997 * @param integer $itemid Item ID that should be added
1998 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2000 public static function distribute($itemid, $signed_text = '')
2002 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2003 $parent = self::selectFirst(['owner-id'], $condition);
2004 if (!DBM::is_result($parent)) {
2008 // Only distribute public items from native networks
2009 $condition = ['id' => $itemid, 'uid' => 0,
2010 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2011 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2012 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2013 if (!DBM::is_result($item)) {
2017 $origin = $item['origin'];
2020 unset($item['parent']);
2021 unset($item['mention']);
2022 unset($item['wall']);
2023 unset($item['origin']);
2024 unset($item['starred']);
2028 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2029 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
2030 $contacts = DBA::select('contact', ['uid'], $condition);
2031 while ($contact = DBA::fetch($contacts)) {
2032 $users[$contact['uid']] = $contact['uid'];
2037 if ($item['uri'] != $item['parent-uri']) {
2038 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2039 while ($parent = DBA::fetch($parents)) {
2040 $users[$parent['uid']] = $parent['uid'];
2041 if ($parent['origin'] && !$origin) {
2042 $origin_uid = $parent['uid'];
2047 foreach ($users as $uid) {
2048 if ($origin_uid == $uid) {
2049 $item['diaspora_signed_text'] = $signed_text;
2051 self::storeForUser($itemid, $item, $uid);
2056 * @brief Store public items for the receivers
2058 * @param integer $itemid Item ID that should be added
2059 * @param array $item The item entry that will be stored
2060 * @param integer $uid The user that will receive the item entry
2062 private static function storeForUser($itemid, $item, $uid)
2064 $item['uid'] = $uid;
2065 $item['origin'] = 0;
2067 if ($item['uri'] == $item['parent-uri']) {
2068 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2070 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2073 if (empty($item['contact-id'])) {
2074 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2075 if (!DBM::is_result($self)) {
2078 $item['contact-id'] = $self['id'];
2081 /// @todo Handling of "event-id"
2084 if ($item['uri'] == $item['parent-uri']) {
2085 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2086 if (DBM::is_result($contact)) {
2087 $notify = self::isRemoteSelf($contact, $item);
2091 $distributed = self::insert($item, false, $notify, true);
2093 if (!$distributed) {
2094 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2096 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2101 * @brief Add a shadow entry for a given item id that is a thread starter
2103 * We store every public item entry additionally with the user id "0".
2104 * This is used for the community page and for the search.
2105 * It is planned that in the future we will store public item entries only once.
2107 * @param integer $itemid Item ID that should be added
2109 public static function addShadow($itemid)
2111 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2112 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2113 $item = self::selectFirst($fields, $condition);
2115 if (!DBM::is_result($item)) {
2119 // is it already a copy?
2120 if (($itemid == 0) || ($item['uid'] == 0)) {
2124 // Is it a visible public post?
2125 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2129 // is it an entry from a connector? Only add an entry for natively connected networks
2130 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2134 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2138 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2140 if (DBM::is_result($item)) {
2141 // Preparing public shadow (removing user specific data)
2144 unset($item['parent']);
2145 unset($item['wall']);
2146 unset($item['mention']);
2147 unset($item['origin']);
2148 unset($item['starred']);
2149 unset($item['postopts']);
2150 unset($item['inform']);
2151 if ($item['uri'] == $item['parent-uri']) {
2152 $item['contact-id'] = $item['owner-id'];
2154 $item['contact-id'] = $item['author-id'];
2157 $public_shadow = self::insert($item, false, false, true);
2159 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2164 * @brief Add a shadow entry for a given item id that is a comment
2166 * This function does the same like the function above - but for comments
2168 * @param integer $itemid Item ID that should be added
2170 public static function addShadowPost($itemid)
2172 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2173 if (!DBM::is_result($item)) {
2177 // Is it a toplevel post?
2178 if ($item['id'] == $item['parent']) {
2179 self::addShadow($itemid);
2183 // Is this a shadow entry?
2184 if ($item['uid'] == 0) {
2188 // Is there a shadow parent?
2189 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2193 // Is there already a shadow entry?
2194 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2198 // Save "origin" and "parent" state
2199 $origin = $item['origin'];
2200 $parent = $item['parent'];
2202 // Preparing public shadow (removing user specific data)
2205 unset($item['parent']);
2206 unset($item['wall']);
2207 unset($item['mention']);
2208 unset($item['origin']);
2209 unset($item['starred']);
2210 unset($item['postopts']);
2211 unset($item['inform']);
2212 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2214 $public_shadow = self::insert($item, false, false, true);
2216 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2218 // If this was a comment to a Diaspora post we don't get our comment back.
2219 // This means that we have to distribute the comment by ourselves.
2220 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2221 self::distribute($public_shadow);
2226 * Adds a language specification in a "language" element of given $arr.
2227 * Expects "body" element to exist in $arr.
2229 private static function addLanguageToItemArray(&$item)
2231 $naked_body = BBCode::toPlaintext($item['body'], false);
2233 $ld = new Text_LanguageDetect();
2234 $ld->setNameMode(2);
2235 $languages = $ld->detect($naked_body, 3);
2237 if (is_array($languages)) {
2238 $item['language'] = json_encode($languages);
2243 * @brief Creates an unique guid out of a given uri
2245 * @param string $uri uri of an item entry
2246 * @param string $host hostname for the GUID prefix
2247 * @return string unique guid
2249 public static function guidFromUri($uri, $host)
2251 // Our regular guid routine is using this kind of prefix as well
2252 // We have to avoid that different routines could accidentally create the same value
2253 $parsed = parse_url($uri);
2255 // We use a hash of the hostname as prefix for the guid
2256 $guid_prefix = hash("crc32", $host);
2258 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2259 unset($parsed["scheme"]);
2261 // Glue it together to be able to make a hash from it
2262 $host_id = implode("/", $parsed);
2264 // We could use any hash algorithm since it isn't a security issue
2265 $host_hash = hash("ripemd128", $host_id);
2267 return $guid_prefix.$host_hash;
2271 * generate an unique URI
2273 * @param integer $uid User id
2274 * @param string $guid An existing GUID (Otherwise it will be generated)
2278 public static function newURI($uid, $guid = "")
2281 $guid = System::createGUID(32);
2284 $hostname = self::getApp()->get_hostname();
2286 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2288 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2294 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2296 * This can be used to filter for inactive contacts.
2297 * Only do this for public postings to avoid privacy problems, since poco data is public.
2298 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2300 * @param array $arr Contains the just posted item record
2302 private static function updateContact($arr)
2304 // Unarchive the author
2305 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2306 if (DBM::is_result($contact)) {
2307 Contact::unmarkForArchival($contact);
2310 // Unarchive the contact if it's not our own contact
2311 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2312 if (DBM::is_result($contact)) {
2313 Contact::unmarkForArchival($contact);
2316 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2318 // Is it a forum? Then we don't care about the rules from above
2319 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2320 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2326 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2327 ['id' => $arr['contact-id']]);
2329 // Now do the same for the system wide contacts with uid=0
2330 if (!$arr['private']) {
2331 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2332 ['id' => $arr['owner-id']]);
2334 if ($arr['owner-id'] != $arr['author-id']) {
2335 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2336 ['id' => $arr['author-id']]);
2341 public static function setHashtags(&$item)
2344 $tags = get_tags($item["body"]);
2347 if (!count($tags)) {
2351 // This sorting is important when there are hashtags that are part of other hashtags
2352 // Otherwise there could be problems with hashtags like #test and #test2
2355 $URLSearchString = "^\[\]";
2357 // All hashtags should point to the home server if "local_tags" is activated
2358 if (Config::get('system', 'local_tags')) {
2359 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2360 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2362 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2363 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2366 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2367 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2369 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2372 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2374 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2377 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2379 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2382 // Repair recursive urls
2383 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2384 "#$2", $item["body"]);
2386 foreach ($tags as $tag) {
2387 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2391 $basetag = str_replace('_',' ',substr($tag,1));
2393 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2395 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2397 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2398 if (strlen($item["tag"])) {
2399 $item["tag"] = ','.$item["tag"];
2401 $item["tag"] = $newtag.$item["tag"];
2405 // Convert back the masked hashtags
2406 $item["body"] = str_replace("#", "#", $item["body"]);
2409 public static function getGuidById($id)
2411 $item = self::selectFirst(['guid'], ['id' => $id]);
2412 if (DBM::is_result($item)) {
2413 return $item['guid'];
2419 public static function getIdAndNickByGuid($guid, $uid = 0)
2425 $uid == local_user();
2428 // Does the given user have this item?
2430 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2431 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2432 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2433 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2434 if (DBM::is_result($item)) {
2436 $nick = $item["nickname"];
2440 // Or is it anywhere on the server?
2442 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2443 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2444 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2445 AND NOT `item`.`private` AND `item`.`wall`
2446 AND `item`.`guid` = ?", $guid);
2447 if (DBM::is_result($item)) {
2449 $nick = $item["nickname"];
2452 return ["nick" => $nick, "id" => $id];
2456 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2458 * @param int $item_id
2459 * @return bool true if item was deleted, else false
2461 private static function tagDeliver($uid, $item_id)
2465 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2466 if (!DBM::is_result($user)) {
2470 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2471 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2473 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2474 if (!DBM::is_result($item)) {
2478 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2481 * Diaspora uses their own hardwired link URL in @-tags
2482 * instead of the one we supply with webfinger
2484 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2486 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2488 foreach ($matches as $mtch) {
2489 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2491 logger('mention found: ' . $mtch[2]);
2497 if (($community_page || $prvgroup) &&
2498 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2499 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2501 logger("no-mention top-level post to community or private group. delete.");
2502 DBA::delete('item', ['id' => $item_id]);
2508 $arr = ['item' => $item, 'user' => $user];
2510 Addon::callHooks('tagged', $arr);
2512 if (!$community_page && !$prvgroup) {
2517 * tgroup delivery - setup a second delivery chain
2518 * prevent delivery looping - only proceed
2519 * if the message originated elsewhere and is a top-level post
2521 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2525 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2526 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2527 if (!DBM::is_result($self)) {
2531 $owner_id = Contact::getIdForURL($self['url']);
2533 // also reset all the privacy bits to the forum default permissions
2535 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2537 $forum_mode = ($prvgroup ? 2 : 1);
2539 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2540 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2541 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2542 DBA::update('item', $fields, ['id' => $item_id]);
2544 self::updateThread($item_id);
2546 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2549 public static function isRemoteSelf($contact, &$datarray)
2553 if (!$contact['remote_self']) {
2557 // Prevent the forwarding of posts that are forwarded
2558 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2559 logger('Already forwarded', LOGGER_DEBUG);
2563 // Prevent to forward already forwarded posts
2564 if ($datarray["app"] == $a->get_hostname()) {
2565 logger('Already forwarded (second test)', LOGGER_DEBUG);
2569 // Only forward posts
2570 if ($datarray["verb"] != ACTIVITY_POST) {
2571 logger('No post', LOGGER_DEBUG);
2575 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2576 logger('Not public', LOGGER_DEBUG);
2580 $datarray2 = $datarray;
2581 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2582 if ($contact['remote_self'] == 2) {
2583 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2584 ['uid' => $contact['uid'], 'self' => true]);
2585 if (DBM::is_result($self)) {
2586 $datarray['contact-id'] = $self["id"];
2588 $datarray['owner-name'] = $self["name"];
2589 $datarray['owner-link'] = $self["url"];
2590 $datarray['owner-avatar'] = $self["thumb"];
2592 $datarray['author-name'] = $datarray['owner-name'];
2593 $datarray['author-link'] = $datarray['owner-link'];
2594 $datarray['author-avatar'] = $datarray['owner-avatar'];
2596 unset($datarray['created']);
2597 unset($datarray['edited']);
2599 unset($datarray['network']);
2600 unset($datarray['owner-id']);
2601 unset($datarray['author-id']);
2604 if ($contact['network'] != NETWORK_FEED) {
2605 $datarray["guid"] = System::createGUID(32);
2606 unset($datarray["plink"]);
2607 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2608 $datarray["parent-uri"] = $datarray["uri"];
2609 $datarray["thr-parent"] = $datarray["uri"];
2610 $datarray["extid"] = NETWORK_DFRN;
2611 $urlpart = parse_url($datarray2['author-link']);
2612 $datarray["app"] = $urlpart["host"];
2614 $datarray['private'] = 0;
2618 if ($contact['network'] != NETWORK_FEED) {
2619 // Store the original post
2620 $result = self::insert($datarray2, false, false);
2621 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2623 $datarray["app"] = "Feed";
2627 // Trigger automatic reactions for addons
2628 $datarray['api_source'] = true;
2630 // We have to tell the hooks who we are - this really should be improved
2631 $_SESSION["authenticated"] = true;
2632 $_SESSION["uid"] = $contact['uid'];
2641 * @param array $item
2645 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2647 if (Config::get('system', 'disable_embedded')) {
2651 logger('check for photos', LOGGER_DEBUG);
2652 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2657 $img_start = strpos($orig_body, '[img');
2658 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2659 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2661 while (($img_st_close !== false) && ($img_len !== false)) {
2662 $img_st_close++; // make it point to AFTER the closing bracket
2663 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2665 logger('found photo ' . $image, LOGGER_DEBUG);
2667 if (stristr($image, $site . '/photo/')) {
2668 // Only embed locally hosted photos
2670 $i = basename($image);
2671 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2672 $x = strpos($i, '-');
2675 $res = substr($i, $x + 1);
2676 $i = substr($i, 0, $x);
2677 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2678 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2679 if (DBM::is_result($photo)) {
2681 * Check to see if we should replace this photo link with an embedded image
2682 * 1. No need to do so if the photo is public
2683 * 2. If there's a contact-id provided, see if they're in the access list
2684 * for the photo. If so, embed it.
2685 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2686 * permissions, regardless of order but first check to see if they're an exact
2687 * match to save some processing overhead.
2689 if (self::hasPermissions($photo)) {
2691 $recips = self::enumeratePermissions($photo);
2692 if (in_array($cid, $recips)) {
2696 if (self::samePermissions($item, $photo)) {
2702 $data = $photo['data'];
2703 $type = $photo['type'];
2705 // If a custom width and height were specified, apply before embedding
2706 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2707 logger('scaling photo', LOGGER_DEBUG);
2709 $width = intval($match[1]);
2710 $height = intval($match[2]);
2712 $Image = new Image($data, $type);
2713 if ($Image->isValid()) {
2714 $Image->scaleDown(max($width, $height));
2715 $data = $Image->asString();
2716 $type = $Image->getType();
2720 logger('replacing photo', LOGGER_DEBUG);
2721 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2722 logger('replaced: ' . $image, LOGGER_DATA);
2728 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2729 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2730 if ($orig_body === false) {
2734 $img_start = strpos($orig_body, '[img');
2735 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2736 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2739 $new_body = $new_body . $orig_body;
2744 private static function hasPermissions($obj)
2746 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2747 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2750 private static function samePermissions($obj1, $obj2)
2752 // first part is easy. Check that these are exactly the same.
2753 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2754 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2755 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2756 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2760 // This is harder. Parse all the permissions and compare the resulting set.
2761 $recipients1 = self::enumeratePermissions($obj1);
2762 $recipients2 = self::enumeratePermissions($obj2);
2766 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2767 return ($recipients1 == $recipients2);
2770 // returns an array of contact-ids that are allowed to see this object
2771 private static function enumeratePermissions($obj)
2773 $allow_people = expand_acl($obj['allow_cid']);
2774 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2775 $deny_people = expand_acl($obj['deny_cid']);
2776 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2777 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2778 $deny = array_unique(array_merge($deny_people, $deny_groups));
2779 $recipients = array_diff($recipients, $deny);
2783 public static function getFeedTags($item)
2787 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2789 for ($x = 0; $x < $cnt; $x ++) {
2790 if ($matches[1][$x]) {
2791 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2796 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2798 for ($x = 0; $x < $cnt; $x ++) {
2799 if ($matches[1][$x]) {
2800 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2807 public static function expire($uid, $days, $network = "", $force = false)
2809 if (!$uid || ($days < 1)) {
2813 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2814 $uid, GRAVITY_PARENT];
2817 * $expire_network_only = save your own wall posts
2818 * and just expire conversations started by others
2820 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2822 if ($expire_network_only) {
2823 $condition[0] .= " AND NOT `wall`";
2826 if ($network != "") {
2827 $condition[0] .= " AND `network` = ?";
2828 $condition[] = $network;
2831 * There is an index "uid_network_received" but not "uid_network_created"
2832 * This avoids the creation of another index just for one purpose.
2833 * And it doesn't really matter wether to look at "received" or "created"
2835 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2836 $condition[] = $days;
2838 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2839 $condition[] = $days;
2842 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2844 if (!DBM::is_result($items)) {
2848 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2850 // Forcing expiring of items - but not notes and marked items
2852 $expire_items = true;
2855 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2856 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2857 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2861 while ($item = Item::fetch($items)) {
2862 // don't expire filed items
2864 if (strpos($item['file'], '[') !== false) {
2868 // Only expire posts, not photos and photo comments
2870 if (!$expire_photos && strlen($item['resource-id'])) {
2872 } elseif (!$expire_starred && intval($item['starred'])) {
2874 } elseif (!$expire_notes && $item['type'] == 'note') {
2876 } elseif (!$expire_items && $item['type'] != 'note') {
2880 self::deleteById($item['id'], PRIORITY_LOW);
2885 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2888 public static function firstPostDate($uid, $wall = false)
2890 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2891 $params = ['order' => ['created' => false]];
2892 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2893 if (DBM::is_result($thread)) {
2894 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2900 * @brief add/remove activity to an item
2902 * Toggle activities as like,dislike,attend of an item
2904 * @param string $item_id
2905 * @param string $verb
2906 * Activity verb. One of
2907 * like, unlike, dislike, undislike, attendyes, unattendyes,
2908 * attendno, unattendno, attendmaybe, unattendmaybe
2909 * @hook 'post_local_end'
2911 * 'post_id' => ID of posted item
2913 public static function performLike($item_id, $verb)
2915 if (!local_user() && !remote_user()) {
2922 $activity = ACTIVITY_LIKE;
2926 $activity = ACTIVITY_DISLIKE;
2930 $activity = ACTIVITY_ATTEND;
2934 $activity = ACTIVITY_ATTENDNO;
2937 case 'unattendmaybe':
2938 $activity = ACTIVITY_ATTENDMAYBE;
2941 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2945 // Enable activity toggling instead of on/off
2946 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2948 logger('like: verb ' . $verb . ' item ' . $item_id);
2950 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2951 if (!DBM::is_result($item)) {
2952 logger('like: unknown item ' . $item_id);
2956 $item_uri = $item['uri'];
2958 $uid = $item['uid'];
2959 if (($uid == 0) && local_user()) {
2960 $uid = local_user();
2963 if (!can_write_wall($uid)) {
2964 logger('like: unable to write on wall ' . $uid);
2968 // Retrieves the local post owner
2969 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2970 if (!DBM::is_result($owner_self_contact)) {
2971 logger('like: unknown owner ' . $uid);
2975 // Retrieve the current logged in user's public contact
2976 $author_id = public_contact();
2978 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
2979 if (!DBM::is_result($author_contact)) {
2980 logger('like: unknown author ' . $author_id);
2984 // Contact-id is the uid-dependant author contact
2985 if (local_user() == $uid) {
2986 $item_contact_id = $owner_self_contact['id'];
2987 $item_contact = $owner_self_contact;
2989 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2990 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
2991 if (!DBM::is_result($item_contact)) {
2992 logger('like: unknown item contact ' . $item_contact_id);
2997 // Look for an existing verb row
2998 // event participation are essentially radio toggles. If you make a subsequent choice,
2999 // we need to eradicate your first choice.
3000 if ($event_verb_flag) {
3001 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3003 // Translate to the index based activity index
3005 foreach ($verbs as $verb) {
3006 $activities[] = self::activityToIndex($verb);
3009 $activities = self::activityToIndex($activity);
3012 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3013 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3015 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3017 // If it exists, mark it as deleted
3018 if (DBM::is_result($like_item)) {
3019 // Already voted, undo it
3020 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
3021 /// @todo Consider using self::update - but before doing so, check the side effects
3022 DBA::update('item', $fields, ['id' => $like_item['id']]);
3024 // Clean up the Diaspora signatures for this like
3025 DBA::delete('sign', ['iid' => $like_item['id']]);
3027 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
3029 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3034 // Verb is "un-something", just trying to delete existing entries
3035 if (strpos($verb, 'un') === 0) {
3039 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3042 'guid' => System::createGUID(32),
3043 'uri' => self::newURI($item['uid']),
3044 'uid' => $item['uid'],
3045 'contact-id' => $item_contact_id,
3046 'wall' => $item['wall'],
3048 'network' => NETWORK_DFRN,
3049 'gravity' => GRAVITY_ACTIVITY,
3050 'parent' => $item['id'],
3051 'parent-uri' => $item['uri'],
3052 'thr-parent' => $item['uri'],
3053 'owner-id' => $item['owner-id'],
3054 'author-id' => $author_id,
3055 'body' => $activity,
3056 'verb' => $activity,
3057 'object-type' => $objtype,
3058 'allow_cid' => $item['allow_cid'],
3059 'allow_gid' => $item['allow_gid'],
3060 'deny_cid' => $item['deny_cid'],
3061 'deny_gid' => $item['deny_gid'],
3066 $new_item_id = self::insert($new_item);
3068 // If the parent item isn't visible then set it to visible
3069 if (!$item['visible']) {
3070 self::update(['visible' => true], ['id' => $item['id']]);
3073 // Save the author information for the like in case we need to relay to Diaspora
3074 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3076 $new_item['id'] = $new_item_id;
3078 Addon::callHooks('post_local_end', $new_item);
3080 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3085 private static function addThread($itemid, $onlyshadow = false)
3087 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3088 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3089 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3090 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3091 $item = self::selectFirst($fields, $condition);
3093 if (!DBM::is_result($item)) {
3097 $item['iid'] = $itemid;
3100 $result = DBA::insert('thread', $item);
3102 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3106 private static function updateThread($itemid, $setmention = false)
3108 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3109 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3110 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3111 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3113 $item = self::selectFirst($fields, $condition);
3114 if (!DBM::is_result($item)) {
3119 $item["mention"] = 1;
3126 foreach ($item as $field => $data) {
3127 if (!in_array($field, ["guid"])) {
3128 $fields[$field] = $data;
3132 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3134 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3137 private static function deleteThread($itemid, $itemuri = "")
3139 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3140 if (!DBM::is_result($item)) {
3141 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3145 // Using dba::delete at this time could delete the associated item entries
3146 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3148 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3150 if ($itemuri != "") {
3151 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3152 if (!self::exists($condition)) {
3153 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3154 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);