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\Object\Image;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\XML;
23 use Text_LanguageDetect;
25 require_once 'boot.php';
26 require_once 'include/items.php';
27 require_once 'include/text.php';
29 class Item extends BaseObject
31 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
38 const PT_DOCUMENT = 19;
40 const PT_PERSONAL_NOTE = 128;
42 // Field list that is used to display the items
43 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
44 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
45 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
46 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
47 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
48 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
49 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
50 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
51 'writable', 'self', 'cid', 'alias',
52 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
53 'event-summary', 'event-desc', 'event-location', 'event-type',
54 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
56 // Field list that is used to deliver items via the protocols
57 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
58 'created', 'edited', 'verb', 'object-type', 'object', 'target',
59 'private', 'title', 'body', 'location', 'coord', 'app',
60 'attach', 'tag', 'deleted', 'extid', 'post-type',
61 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
62 'author-id', 'author-link', 'owner-link', 'contact-uid',
63 'signed_text', 'signature', 'signer', 'network'];
65 // Field list for "item-content" table that is mixed with the item table
66 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
67 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
68 'object-type', 'object', 'target-type', 'target', 'plink'];
70 // Field list for "item-content" table that is not present in the "item" table
71 const CONTENT_FIELDLIST = ['language'];
73 // Field list for additional delivery data
74 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
76 // All fields in the item table
77 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
78 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
79 'created', 'edited', 'commented', 'received', 'changed', 'verb',
80 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
81 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
82 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
83 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
84 'title', 'content-warning', 'body', 'location', 'coord', 'app',
85 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
86 'author-id', 'author-link', 'author-name', 'author-avatar',
87 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
89 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
90 // The item-activity table only stores the index and needs this array to know the matching activity.
91 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
93 private static $legacy_mode = null;
95 public static function isLegacyMode()
97 if (is_null(self::$legacy_mode)) {
98 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
101 return self::$legacy_mode;
105 * @brief returns an activity index from an activity string
107 * @param string $activity activity string
108 * @return integer Activity index
110 private static function activityToIndex($activity)
112 $index = array_search($activity, self::ACTIVITIES);
114 if (is_bool($index)) {
122 * @brief returns an activity string from an activity index
124 * @param integer $index activity index
125 * @return string Activity string
127 private static function indexToActivity($index)
129 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
133 return self::ACTIVITIES[$index];
137 * @brief Fetch a single item row
139 * @param mixed $stmt statement object
140 * @return array current row
142 public static function fetch($stmt)
144 $row = DBA::fetch($stmt);
150 // ---------------------- Transform item structure data ----------------------
152 // We prefer the data from the user's contact over the public one
153 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
154 ($row['author-link'] == $row['contact-link'])) {
155 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
156 $row['author-avatar'] = $row['contact-avatar'];
158 if (isset($row['author-name']) && !empty($row['contact-name'])) {
159 $row['author-name'] = $row['contact-name'];
163 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
164 ($row['owner-link'] == $row['contact-link'])) {
165 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
166 $row['owner-avatar'] = $row['contact-avatar'];
168 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
169 $row['owner-name'] = $row['contact-name'];
173 // We can always comment on posts from these networks
174 if (array_key_exists('writable', $row) &&
175 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
176 $row['writable'] = true;
179 // ---------------------- Transform item content data ----------------------
181 // Fetch data from the item-content table whenever there is content there
182 if (self::isLegacyMode()) {
183 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
184 foreach ($legacy_fields as $field) {
185 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
186 $row[$field] = $row['internal-item-' . $field];
188 unset($row['internal-item-' . $field]);
192 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
193 $row['verb'] = self::indexToActivity($row['internal-activity']);
194 if (array_key_exists('title', $row)) {
197 if (array_key_exists('body', $row)) {
198 $row['body'] = $row['verb'];
200 if (array_key_exists('object', $row)) {
203 if (array_key_exists('object-type', $row)) {
204 $row['object-type'] = ACTIVITY_OBJ_NOTE;
206 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
207 // Posts don't have an object or target - but having tags or files.
208 // We safe some performance by building tag and file strings only here.
209 // We remove object and target since they aren't used for this type.
210 if (array_key_exists('object', $row)) {
213 if (array_key_exists('target', $row)) {
218 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
219 // Build the tag string out of the term entries
220 if (array_key_exists('tag', $row) && empty($row['tag'])) {
221 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
224 // Build the file string out of the term entries
225 if (array_key_exists('file', $row) && empty($row['file'])) {
226 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
230 // Remove internal fields
231 unset($row['internal-activity']);
232 unset($row['internal-network']);
233 unset($row['internal-iid']);
234 unset($row['internal-iaid']);
235 unset($row['internal-icid']);
241 * @brief Fills an array with data from an item query
243 * @param object $stmt statement object
244 * @return array Data array
246 public static function inArray($stmt, $do_close = true) {
247 if (is_bool($stmt)) {
252 while ($row = self::fetch($stmt)) {
262 * @brief Check if item data exists
264 * @param array $condition array of fields for condition
266 * @return boolean Are there rows for that condition?
268 public static function exists($condition) {
269 $stmt = self::select(['id'], $condition, ['limit' => 1]);
271 if (is_bool($stmt)) {
274 $retval = (DBA::numRows($stmt) > 0);
283 * Retrieve a single record from the item table for a given user and returns it in an associative array
285 * @brief Retrieve a single record from a table
286 * @param integer $uid User ID
287 * @param array $fields
288 * @param array $condition
289 * @param array $params
293 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
295 $params['uid'] = $uid;
297 if (empty($selected)) {
298 $selected = Item::DISPLAY_FIELDLIST;
301 return self::selectFirst($selected, $condition, $params);
305 * @brief Select rows from the item table for a given user
307 * @param integer $uid User ID
308 * @param array $selected Array of selected fields, empty for all
309 * @param array $condition Array of fields for condition
310 * @param array $params Array of several parameters
312 * @return boolean|object
314 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
316 $params['uid'] = $uid;
318 if (empty($selected)) {
319 $selected = Item::DISPLAY_FIELDLIST;
322 return self::select($selected, $condition, $params);
326 * Retrieve a single record from the item table and returns it in an associative array
328 * @brief Retrieve a single record from a table
329 * @param array $fields
330 * @param array $condition
331 * @param array $params
335 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
337 $params['limit'] = 1;
339 $result = self::select($fields, $condition, $params);
341 if (is_bool($result)) {
344 $row = self::fetch($result);
351 * @brief Select rows from the item table
353 * @param array $selected Array of selected fields, empty for all
354 * @param array $condition Array of fields for condition
355 * @param array $params Array of several parameters
357 * @return boolean|object
359 public static function select(array $selected = [], array $condition = [], $params = [])
364 if (isset($params['uid'])) {
365 $uid = $params['uid'];
369 $fields = self::fieldlist($selected);
371 $select_fields = self::constructSelectFields($fields, $selected);
373 $condition_string = DBA::buildCondition($condition);
375 $condition_string = self::addTablesToFields($condition_string, $fields);
378 $condition_string = $condition_string . ' AND ' . self::condition(false);
381 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
383 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
385 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
387 return DBA::p($sql, $condition);
391 * @brief Select rows from the starting post in the item table
393 * @param integer $uid User ID
394 * @param array $fields Array of selected fields, empty for all
395 * @param array $condition Array of fields for condition
396 * @param array $params Array of several parameters
398 * @return boolean|object
400 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
402 $params['uid'] = $uid;
404 if (empty($selected)) {
405 $selected = Item::DISPLAY_FIELDLIST;
408 return self::selectThread($selected, $condition, $params);
412 * Retrieve a single record from the starting post in the item table and returns it in an associative array
414 * @brief Retrieve a single record from a table
415 * @param integer $uid User ID
416 * @param array $selected
417 * @param array $condition
418 * @param array $params
422 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
424 $params['uid'] = $uid;
426 if (empty($selected)) {
427 $selected = Item::DISPLAY_FIELDLIST;
430 return self::selectFirstThread($selected, $condition, $params);
434 * Retrieve a single record from the starting post in the item table and returns it in an associative array
436 * @brief Retrieve a single record from a table
437 * @param array $fields
438 * @param array $condition
439 * @param array $params
443 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
445 $params['limit'] = 1;
446 $result = self::selectThread($fields, $condition, $params);
448 if (is_bool($result)) {
451 $row = self::fetch($result);
458 * @brief Select rows from the starting post in the item table
460 * @param array $selected Array of selected fields, empty for all
461 * @param array $condition Array of fields for condition
462 * @param array $params Array of several parameters
464 * @return boolean|object
466 public static function selectThread(array $selected = [], array $condition = [], $params = [])
471 if (isset($params['uid'])) {
472 $uid = $params['uid'];
476 $fields = self::fieldlist($selected);
478 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
479 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
480 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
481 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
483 $select_fields = self::constructSelectFields($fields, $selected);
485 $condition_string = DBA::buildCondition($condition);
487 $condition_string = self::addTablesToFields($condition_string, $threadfields);
488 $condition_string = self::addTablesToFields($condition_string, $fields);
491 $condition_string = $condition_string . ' AND ' . self::condition(true);
494 $param_string = DBA::buildParameter($params);
495 $param_string = self::addTablesToFields($param_string, $threadfields);
496 $param_string = self::addTablesToFields($param_string, $fields);
498 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
500 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
502 return DBA::p($sql, $condition);
506 * @brief Returns a list of fields that are associated with the item table
508 * @return array field list
510 private static function fieldlist($selected)
514 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
515 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
516 'created', 'edited', 'commented', 'received', 'changed',
517 'resource-id', 'event-id', 'tag', 'attach', 'post-type',
518 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid',
519 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
520 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
521 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
522 'network' => 'internal-network', 'icid' => 'internal-icid',
523 'iaid' => 'internal-iaid'];
525 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
527 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
529 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
531 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
532 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
534 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
535 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
537 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
538 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
539 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
541 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
543 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
545 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
546 'start' => 'event-start','finish' => 'event-finish',
547 'summary' => 'event-summary','desc' => 'event-desc',
548 'location' => 'event-location', 'type' => 'event-type',
549 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
550 'ignore' => 'event-ignore', 'id' => 'event-id'];
552 $fields['sign'] = ['signed_text', 'signature', 'signer'];
558 * @brief Returns SQL condition for the "select" functions
560 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
562 * @return string SQL condition
564 private static function condition($thread_mode)
567 $master_table = "`thread`";
569 $master_table = "`item`";
571 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`) ";
575 * @brief Returns all needed "JOIN" commands for the "select" functions
577 * @param integer $uid User ID
578 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
579 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
581 * @return string The SQL joins for the "select" functions
583 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
586 $master_table = "`thread`";
587 $master_table_key = "`thread`.`iid`";
588 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
590 $master_table = "`item`";
591 $master_table_key = "`item`.`id`";
596 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
597 AND NOT `contact`.`blocked`
598 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
599 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
600 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
601 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
602 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
603 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, GRAVITY_PARENT, intval($uid));
605 if (strpos($sql_commands, "`contact`.") !== false) {
606 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
608 if (strpos($sql_commands, "`author`.") !== false) {
609 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
611 if (strpos($sql_commands, "`owner`.") !== false) {
612 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
616 if (strpos($sql_commands, "`group_member`.") !== false) {
617 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
620 if (strpos($sql_commands, "`user`.") !== false) {
621 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
624 if (strpos($sql_commands, "`event`.") !== false) {
625 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
628 if (strpos($sql_commands, "`sign`.") !== false) {
629 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
632 if (strpos($sql_commands, "`item-activity`.") !== false) {
633 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
636 if (strpos($sql_commands, "`item-content`.") !== false) {
637 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
640 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
641 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
644 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
645 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
648 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
649 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
656 * @brief Add the field list for the "select" functions
658 * @param array $fields The field definition array
659 * @param array $selected The array with the selected fields from the "select" functions
661 * @return string The field list
663 private static function constructSelectFields($fields, $selected)
665 if (!empty($selected)) {
666 $selected[] = 'internal-iid';
667 $selected[] = 'internal-iaid';
668 $selected[] = 'internal-icid';
669 $selected[] = 'internal-network';
672 if (in_array('verb', $selected)) {
673 $selected[] = 'internal-activity';
677 foreach ($fields as $table => $table_fields) {
678 foreach ($table_fields as $field => $select) {
679 if (empty($selected) || in_array($select, $selected)) {
680 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
681 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
682 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
684 if (is_int($field)) {
685 $selection[] = "`" . $table . "`.`" . $select . "`";
687 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
692 return implode(", ", $selection);
696 * @brief add table definition to fields in an SQL query
698 * @param string $query SQL query
699 * @param array $fields The field definition array
701 * @return string the changed SQL query
703 private static function addTablesToFields($query, $fields)
705 foreach ($fields as $table => $table_fields) {
706 foreach ($table_fields as $alias => $field) {
707 if (is_int($alias)) {
708 $replace_field = $field;
710 $replace_field = $alias;
713 $search = "/([^\.])`" . $field . "`/i";
714 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
715 $query = preg_replace($search, $replace, $query);
722 * @brief Generate a server unique item hash for linking between the item tables
724 * @param string $uri Item URI
725 * @param date $created Item creation date
727 * @return string the item hash
729 private static function itemHash($uri, $created)
731 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
735 * @brief Update existing item entries
737 * @param array $fields The fields that are to be changed
738 * @param array $condition The condition for finding the item entries
740 * In the future we may have to change permissions as well.
741 * Then we had to add the user id as third parameter.
743 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
745 * @return integer|boolean number of affected rows - or "false" if there was an error
747 public static function update(array $fields, array $condition)
749 if (empty($condition) || empty($fields)) {
753 // To ensure the data integrity we do it in an transaction
756 // We cannot simply expand the condition to check for origin entries
757 // The condition needn't to be a simple array but could be a complex condition.
758 // And we have to execute this query before the update to ensure to fetch the same data.
759 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
761 $content_fields = [];
762 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
763 if (isset($fields[$field])) {
764 $content_fields[$field] = $fields[$field];
765 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
766 unset($fields[$field]);
768 $fields[$field] = null;
773 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
774 foreach ($clear_fields as $field) {
775 if (array_key_exists($field, $fields)) {
776 $fields[$field] = null;
780 if (array_key_exists('tag', $fields)) {
781 $tags = $fields['tag'];
782 $fields['tag'] = null;
787 if (array_key_exists('file', $fields)) {
788 $files = $fields['file'];
789 $fields['file'] = null;
794 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
795 'inform' => defaults($fields, 'inform', '')];
797 $fields['postopts'] = null;
798 $fields['inform'] = null;
800 if (!empty($fields)) {
801 $success = DBA::update('item', $fields, $condition);
810 // When there is no content for the "old" item table, this will count the fetched items
811 $rows = DBA::affectedRows();
813 while ($item = DBA::fetch($items)) {
815 // This part here can safely be removed when the legacy fields in the item had been removed
816 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
818 // Fetch the uri-hash from an existing item entry if there is one
819 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
820 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
821 if (DBA::isResult($existing)) {
822 $item['uri-hash'] = $existing['uri-hash'];
824 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
827 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
828 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
829 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
832 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
833 if (!empty($item['iaid'])) {
834 $update_condition = ['id' => $item['iaid']];
836 $update_condition = ['uri-hash' => $item['uri-hash']];
838 self::updateActivity($content_fields, $update_condition);
840 if (empty($item['iaid'])) {
841 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
842 if (DBA::isResult($item_activity)) {
843 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
844 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
845 if (self::isLegacyMode()) {
846 $item_fields[$field] = null;
848 unset($item_fields[$field]);
851 DBA::update('item', $item_fields, ['id' => $item['id']]);
853 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
854 DBA::delete('item-content', ['id' => $item['icid']]);
857 } elseif (!empty($item['icid'])) {
858 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
860 if (!DBA::exists('item', ['icid' => $item['icid']])) {
861 DBA::delete('item-content', ['id' => $item['icid']]);
865 if (!empty($item['icid'])) {
866 $update_condition = ['id' => $item['icid']];
868 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
870 self::updateContent($content_fields, $update_condition);
872 if (empty($item['icid'])) {
873 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
874 if (DBA::isResult($item_content)) {
875 $item_fields = ['icid' => $item_content['id']];
876 // Clear all fields in the item table that have a content in the item-content table
877 foreach ($item_content as $field => $content) {
878 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
879 if (self::isLegacyMode()) {
880 $item_fields[$field] = null;
882 unset($item_fields[$field]);
886 DBA::update('item', $item_fields, ['id' => $item['id']]);
892 Term::insertFromTagFieldByItemId($item['id'], $tags);
893 if (!empty($item['tag'])) {
894 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
898 if (!empty($files)) {
899 Term::insertFromFileFieldByItemId($item['id'], $files);
900 if (!empty($item['file'])) {
901 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
905 self::updateDeliveryData($item['id'], $delivery_data);
907 self::updateThread($item['id']);
909 // We only need to notfiy others when it is an original entry from us.
910 // Only call the notifier when the item has some content relevant change.
911 if ($item['origin'] && in_array('edited', array_keys($fields))) {
912 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
922 * @brief Delete an item and notify others about it - if it was ours
924 * @param array $condition The condition for finding the item entries
925 * @param integer $priority Priority for the notification
927 public static function delete($condition, $priority = PRIORITY_HIGH)
929 $items = DBA::select('item', ['id'], $condition);
930 while ($item = DBA::fetch($items)) {
931 self::deleteById($item['id'], $priority);
937 * @brief Delete an item for an user and notify others about it - if it was ours
939 * @param array $condition The condition for finding the item entries
940 * @param integer $uid User who wants to delete this item
942 public static function deleteForUser($condition, $uid)
948 $items = DBA::select('item', ['id', 'uid'], $condition);
949 while ($item = DBA::fetch($items)) {
950 // "Deleting" global items just means hiding them
951 if ($item['uid'] == 0) {
952 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
953 } elseif ($item['uid'] == $uid) {
954 self::deleteById($item['id'], PRIORITY_HIGH);
956 logger('Wrong ownership. Not deleting item ' . $item['id']);
963 * @brief Delete an item and notify others about it - if it was ours
965 * @param integer $item_id Item ID that should be delete
966 * @param integer $priority Priority for the notification
968 * @return boolean success
970 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
972 // locate item to be deleted
973 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
974 'deleted', 'file', 'resource-id', 'event-id', 'attach',
975 'verb', 'object-type', 'object', 'target', 'contact-id'];
976 $item = self::selectFirst($fields, ['id' => $item_id]);
977 if (!DBA::isResult($item)) {
978 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
982 if ($item['deleted']) {
983 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
987 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
988 if (!DBA::isResult($parent)) {
989 $parent = ['origin' => false];
992 // clean up categories and tags so they don't end up as orphans
995 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
997 foreach ($matches as $mtch) {
998 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1004 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1006 foreach ($matches as $mtch) {
1007 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1012 * If item is a link to a photo resource, nuke all the associated photos
1013 * (visitors will not have photo resources)
1014 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1015 * generate a resource-id and therefore aren't intimately linked to the item.
1017 if (strlen($item['resource-id'])) {
1018 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1021 // If item is a link to an event, delete the event.
1022 if (intval($item['event-id'])) {
1023 Event::delete($item['event-id']);
1026 // If item has attachments, drop them
1027 foreach (explode(", ", $item['attach']) as $attach) {
1028 preg_match("|attach/(\d+)|", $attach, $matches);
1029 if (is_array($matches) && count($matches) > 1) {
1030 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1034 // Delete tags that had been attached to other items
1035 self::deleteTagsFromItem($item);
1037 // Set the item to "deleted"
1038 // This erasing of item content is superfluous for items with a matching item-content.
1039 // But for the next time we will still have old content in the item table.
1040 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
1041 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
1042 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
1043 DBA::update('item', $item_fields, ['id' => $item['id']]);
1045 Term::insertFromTagFieldByItemId($item['id'], '');
1046 Term::insertFromFileFieldByItemId($item['id'], '');
1047 self::deleteThread($item['id'], $item['parent-uri']);
1049 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1050 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1053 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1055 // If it's the parent of a comment thread, kill all the kids
1056 if ($item['id'] == $item['parent']) {
1057 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1060 // Is it our comment and/or our thread?
1061 if ($item['origin'] || $parent['origin']) {
1063 // When we delete the original post we will delete all existing copies on the server as well
1064 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1066 // send the notification upstream/downstream
1067 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1068 } elseif ($item['uid'] != 0) {
1070 // When we delete just our local user copy of an item, we have to set a marker to hide it
1071 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1072 if (DBA::isResult($global_item)) {
1073 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1077 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1082 private static function deleteTagsFromItem($item)
1084 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1088 $xo = XML::parseString($item["object"], false);
1089 $xt = XML::parseString($item["target"], false);
1091 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1095 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1096 if (!DBA::isResult($i)) {
1100 // For tags, the owner cannot remove the tag on the author's copy of the post.
1101 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1102 $author_copy = $item["origin"];
1104 if (($owner_remove && $author_copy) || !$owner_remove) {
1108 $tags = explode(',', $i["tag"]);
1111 foreach ($tags as $tag) {
1112 if (trim($tag) !== trim($xo->body)) {
1113 $newtags[] = trim($tag);
1117 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1120 private static function guid($item, $notify)
1122 if (!empty($item['guid'])) {
1123 return notags(trim($item['guid']));
1127 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1128 // We add the hash of our own host because our host is the original creator of the post.
1129 $prefix_host = get_app()->get_hostname();
1133 // We are only storing the post so we create a GUID from the original hostname.
1134 if (!empty($item['author-link'])) {
1135 $parsed = parse_url($item['author-link']);
1136 if (!empty($parsed['host'])) {
1137 $prefix_host = $parsed['host'];
1141 if (empty($prefix_host) && !empty($item['plink'])) {
1142 $parsed = parse_url($item['plink']);
1143 if (!empty($parsed['host'])) {
1144 $prefix_host = $parsed['host'];
1148 if (empty($prefix_host) && !empty($item['uri'])) {
1149 $parsed = parse_url($item['uri']);
1150 if (!empty($parsed['host'])) {
1151 $prefix_host = $parsed['host'];
1155 // Is it in the format data@host.tld? - Used for mail contacts
1156 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1157 $mailparts = explode('@', $item['author-link']);
1158 $prefix_host = array_pop($mailparts);
1162 if (!empty($item['plink'])) {
1163 $guid = self::guidFromUri($item['plink'], $prefix_host);
1164 } elseif (!empty($item['uri'])) {
1165 $guid = self::guidFromUri($item['uri'], $prefix_host);
1167 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1173 private static function contactId($item)
1175 $contact_id = (int)$item["contact-id"];
1177 if (!empty($contact_id)) {
1180 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1182 * First we are looking for a suitable contact that matches with the author of the post
1183 * This is done only for comments
1185 if ($item['parent-uri'] != $item['uri']) {
1186 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1189 // If not present then maybe the owner was found
1190 if ($contact_id == 0) {
1191 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1194 // Still missing? Then use the "self" contact of the current user
1195 if ($contact_id == 0) {
1196 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1197 if (DBA::isResult($self)) {
1198 $contact_id = $self["id"];
1201 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1206 // This function will finally cover most of the preparation functionality in mod/item.php
1207 public static function prepare(&$item)
1209 $data = BBCode::getAttachmentData($item['body']);
1210 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1211 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1212 $posttype = Item::PT_PAGE;
1213 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1217 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1221 // If it is a posting where users should get notifications, then define it as wall posting
1224 $item['origin'] = 1;
1225 $item['network'] = NETWORK_DFRN;
1226 $item['protocol'] = PROTOCOL_DFRN;
1228 if (is_int($notify)) {
1229 $priority = $notify;
1231 $priority = PRIORITY_HIGH;
1234 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1237 $item['guid'] = self::guid($item, $notify);
1238 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1240 // Store conversation data
1241 $item = Conversation::insert($item);
1244 * If a Diaspora signature structure was passed in, pull it out of the
1245 * item array and set it aside for later storage.
1249 if (x($item, 'dsprsig')) {
1250 $encoded_signature = $item['dsprsig'];
1251 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1252 unset($item['dsprsig']);
1255 if (!empty($item['diaspora_signed_text'])) {
1256 $diaspora_signed_text = $item['diaspora_signed_text'];
1257 unset($item['diaspora_signed_text']);
1259 $diaspora_signed_text = '';
1262 // Converting the plink
1263 /// @TODO Check if this is really still needed
1264 if ($item['network'] == NETWORK_OSTATUS) {
1265 if (isset($item['plink'])) {
1266 $item['plink'] = OStatus::convertHref($item['plink']);
1267 } elseif (isset($item['uri'])) {
1268 $item['plink'] = OStatus::convertHref($item['uri']);
1272 if (!empty($item['thr-parent'])) {
1273 $item['parent-uri'] = $item['thr-parent'];
1276 if (isset($item['gravity'])) {
1277 $item['gravity'] = intval($item['gravity']);
1278 } elseif ($item['parent-uri'] === $item['uri']) {
1279 $item['gravity'] = GRAVITY_PARENT;
1280 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1281 $item['gravity'] = GRAVITY_COMMENT;
1283 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1284 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1287 $uid = intval($item['uid']);
1289 // check for create date and expire time
1290 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1292 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1293 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1294 $expire_interval = $user['expire'];
1297 if (($expire_interval > 0) && !empty($item['created'])) {
1298 $expire_date = time() - ($expire_interval * 86400);
1299 $created_date = strtotime($item['created']);
1300 if ($created_date < $expire_date) {
1301 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1307 * Do we already have this item?
1308 * We have to check several networks since Friendica posts could be repeated
1309 * via OStatus (maybe Diasporsa as well)
1311 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1312 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1313 trim($item['uri']), $item['uid'],
1314 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1315 $existing = self::selectFirst(['id', 'network'], $condition);
1316 if (DBA::isResult($existing)) {
1317 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1319 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1322 return $existing["id"];
1326 // Ensure to always have the same creation date.
1327 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1328 if (DBA::isResult($existing)) {
1329 $item['created'] = $existing['created'];
1330 $item['uri-hash'] = $existing['uri-hash'];
1333 self::addLanguageToItemArray($item);
1335 $item['wall'] = intval(defaults($item, 'wall', 0));
1336 $item['extid'] = trim(defaults($item, 'extid', ''));
1337 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1338 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1339 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1340 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1341 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1342 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1343 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1344 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1345 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1346 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1347 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1348 $item['title'] = trim(defaults($item, 'title', ''));
1349 $item['location'] = trim(defaults($item, 'location', ''));
1350 $item['coord'] = trim(defaults($item, 'coord', ''));
1351 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1352 $item['deleted'] = 0;
1353 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1354 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1355 $item['verb'] = trim(defaults($item, 'verb', ''));
1356 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1357 $item['object'] = trim(defaults($item, 'object', ''));
1358 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1359 $item['target'] = trim(defaults($item, 'target', ''));
1360 $item['plink'] = trim(defaults($item, 'plink', ''));
1361 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1362 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1363 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1364 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1365 $item['private'] = intval(defaults($item, 'private', 0));
1366 $item['body'] = trim(defaults($item, 'body', ''));
1367 $item['tag'] = trim(defaults($item, 'tag', ''));
1368 $item['attach'] = trim(defaults($item, 'attach', ''));
1369 $item['app'] = trim(defaults($item, 'app', ''));
1370 $item['origin'] = intval(defaults($item, 'origin', 0));
1371 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1372 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1373 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1374 $item['inform'] = trim(defaults($item, 'inform', ''));
1375 $item['file'] = trim(defaults($item, 'file', ''));
1377 // Unique identifier to be linked against item-activities and item-content
1378 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1380 // When there is no content then we don't post it
1381 if ($item['body'].$item['title'] == '') {
1382 logger('No body, no title.');
1386 // Items cannot be stored before they happen ...
1387 if ($item['created'] > DateTimeFormat::utcNow()) {
1388 $item['created'] = DateTimeFormat::utcNow();
1391 // We haven't invented time travel by now.
1392 if ($item['edited'] > DateTimeFormat::utcNow()) {
1393 $item['edited'] = DateTimeFormat::utcNow();
1396 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1398 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1399 $item["contact-id"] = self::contactId($item);
1401 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1402 'photo' => $item['author-avatar'], 'network' => $item['network']];
1404 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1406 if (Contact::isBlocked($item["author-id"])) {
1407 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1411 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1412 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1414 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1416 if (Contact::isBlocked($item["owner-id"])) {
1417 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1421 // These fields aren't stored anymore in the item table, they are fetched upon request
1422 unset($item['author-link']);
1423 unset($item['author-name']);
1424 unset($item['author-avatar']);
1426 unset($item['owner-link']);
1427 unset($item['owner-name']);
1428 unset($item['owner-avatar']);
1430 if ($item['network'] == NETWORK_PHANTOM) {
1431 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1433 $item['network'] = NETWORK_DFRN;
1434 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1437 // Checking if there is already an item with the same guid
1438 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1439 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1440 if (self::exists($condition)) {
1441 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1445 // Check for hashtags in the body and repair or add hashtag links
1446 self::setHashtags($item);
1448 $item['thr-parent'] = $item['parent-uri'];
1456 if ($item['parent-uri'] === $item['uri']) {
1458 $parent_deleted = 0;
1459 $allow_cid = $item['allow_cid'];
1460 $allow_gid = $item['allow_gid'];
1461 $deny_cid = $item['deny_cid'];
1462 $deny_gid = $item['deny_gid'];
1463 $notify_type = 'wall-new';
1465 // find the parent and snarf the item id and ACLs
1466 // and anything else we need to inherit
1468 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1469 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1470 'wall', 'private', 'forum_mode', 'origin'];
1471 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1472 $params = ['order' => ['id' => false]];
1473 $parent = self::selectFirst($fields, $condition, $params);
1475 if (DBA::isResult($parent)) {
1476 // is the new message multi-level threaded?
1477 // even though we don't support it now, preserve the info
1478 // and re-attach to the conversation parent.
1480 if ($parent['uri'] != $parent['parent-uri']) {
1481 $item['parent-uri'] = $parent['parent-uri'];
1483 $condition = ['uri' => $item['parent-uri'],
1484 'parent-uri' => $item['parent-uri'],
1485 'uid' => $item['uid']];
1486 $params = ['order' => ['id' => false]];
1487 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1489 if (DBA::isResult($toplevel_parent)) {
1490 $parent = $toplevel_parent;
1494 $parent_id = $parent['id'];
1495 $parent_deleted = $parent['deleted'];
1496 $allow_cid = $parent['allow_cid'];
1497 $allow_gid = $parent['allow_gid'];
1498 $deny_cid = $parent['deny_cid'];
1499 $deny_gid = $parent['deny_gid'];
1500 $item['wall'] = $parent['wall'];
1501 $notify_type = 'comment-new';
1504 * If the parent is private, force privacy for the entire conversation
1505 * This differs from the above settings as it subtly allows comments from
1506 * email correspondents to be private even if the overall thread is not.
1508 if ($parent['private']) {
1509 $item['private'] = $parent['private'];
1513 * Edge case. We host a public forum that was originally posted to privately.
1514 * The original author commented, but as this is a comment, the permissions
1515 * weren't fixed up so it will still show the comment as private unless we fix it here.
1517 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1518 $item['private'] = 0;
1521 // If its a post from myself then tag the thread as "mention"
1522 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1523 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1524 if (DBA::isResult($user)) {
1525 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1526 $self_id = Contact::getIdForURL($self, 0, true);
1527 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1528 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1529 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1530 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1535 * Allow one to see reply tweets from status.net even when
1536 * we don't have or can't see the original post.
1538 if ($force_parent) {
1539 logger('$force_parent=true, reply converted to top-level post.');
1541 $item['parent-uri'] = $item['uri'];
1542 $item['gravity'] = GRAVITY_PARENT;
1544 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1548 $parent_deleted = 0;
1552 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1553 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1554 if (self::exists($condition)) {
1555 logger('duplicated item with the same uri found. '.print_r($item,true));
1559 // On Friendica and Diaspora the GUID is unique
1560 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1561 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1562 if (self::exists($condition)) {
1563 logger('duplicated item with the same guid found. '.print_r($item,true));
1567 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1568 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1569 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1570 if (self::exists($condition)) {
1571 logger('duplicated item with the same body found. '.print_r($item,true));
1576 // Is this item available in the global items (with uid=0)?
1577 if ($item["uid"] == 0) {
1578 $item["global"] = true;
1580 // Set the global flag on all items if this was a global item entry
1581 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1583 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1587 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1590 $private = $item['private'];
1593 $item["allow_cid"] = $allow_cid;
1594 $item["allow_gid"] = $allow_gid;
1595 $item["deny_cid"] = $deny_cid;
1596 $item["deny_gid"] = $deny_gid;
1597 $item["private"] = $private;
1598 $item["deleted"] = $parent_deleted;
1600 // Fill the cache field
1601 put_item_in_cache($item);
1604 $item['edit'] = false;
1605 $item['parent'] = $parent_id;
1606 Addon::callHooks('post_local', $item);
1607 unset($item['edit']);
1608 unset($item['parent']);
1610 Addon::callHooks('post_remote', $item);
1613 // This array field is used to trigger some automatic reactions
1614 // It is mainly used in the "post_local" hook.
1615 unset($item['api_source']);
1617 if (x($item, 'cancel')) {
1618 logger('post cancelled by addon.');
1623 * Check for already added items.
1624 * There is a timing issue here that sometimes creates double postings.
1625 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1627 if ($item["uid"] == 0) {
1628 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1629 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1634 logger('' . print_r($item,true), LOGGER_DATA);
1636 if (array_key_exists('tag', $item)) {
1637 $tags = $item['tag'];
1638 unset($item['tag']);
1643 if (array_key_exists('file', $item)) {
1644 $files = $item['file'];
1645 unset($item['file']);
1650 // Creates the permission set
1651 // Currently we only store the data but don't using it
1652 $item['psid'] = PermissionSet::fetchIDForPost($item);
1654 // We are doing this outside of the transaction to avoid timing problems
1655 if (!self::insertActivity($item)) {
1656 self::insertContent($item);
1659 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1660 'inform' => defaults($item, 'inform', '')];
1662 unset($item['postopts']);
1663 unset($item['inform']);
1666 $ret = DBA::insert('item', $item);
1668 // When the item was successfully stored we fetch the ID of the item.
1669 if (DBA::isResult($ret)) {
1670 $current_post = DBA::lastInsertId();
1672 // This can happen - for example - if there are locking timeouts.
1675 // Store the data into a spool file so that we can try again later.
1677 // At first we restore the Diaspora signature that we removed above.
1678 if (isset($encoded_signature)) {
1679 $item['dsprsig'] = $encoded_signature;
1682 // Now we store the data in the spool directory
1683 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1684 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1686 $spoolpath = get_spoolpath();
1687 if ($spoolpath != "") {
1688 $spool = $spoolpath.'/'.$file;
1690 // Ensure to have the removed data from above again in the item array
1691 $item = array_merge($item, $delivery_data);
1693 file_put_contents($spool, json_encode($item));
1694 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1699 if ($current_post == 0) {
1700 // This is one of these error messages that never should occur.
1701 logger("couldn't find created item - we better quit now.");
1706 // How much entries have we created?
1707 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1708 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1711 // There are duplicates. We delete our just created entry.
1712 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1714 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1715 DBA::delete('item', ['id' => $current_post]);
1718 } elseif ($entries == 0) {
1719 // This really should never happen since we quit earlier if there were problems.
1720 logger("Something is terribly wrong. We haven't found our created entry.");
1725 logger('created item '.$current_post);
1726 self::updateContact($item);
1728 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1729 $parent_id = $current_post;
1733 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1735 $item['id'] = $current_post;
1736 $item['parent'] = $parent_id;
1738 // update the commented timestamp on the parent
1739 // Only update "commented" if it is really a comment
1740 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1741 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1743 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1748 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1749 * We can check for this condition when we decode and encode the stuff again.
1751 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1752 $dsprsig->signature = base64_decode($dsprsig->signature);
1753 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1756 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1757 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1760 if (!empty($diaspora_signed_text)) {
1761 // Formerly we stored the signed text, the signature and the author in different fields.
1762 // We now store the raw data so that we are more flexible.
1763 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1766 $deleted = self::tagDeliver($item['uid'], $current_post);
1769 * current post can be deleted if is for a community page and no mention are
1772 if (!$deleted && !$dontcache) {
1773 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1774 if (DBA::isResult($posted_item)) {
1776 Addon::callHooks('post_local_end', $posted_item);
1778 Addon::callHooks('post_remote_end', $posted_item);
1781 logger('new item not found in DB, id ' . $current_post);
1785 if ($item['parent-uri'] === $item['uri']) {
1786 self::addThread($current_post);
1788 self::updateThread($parent_id);
1791 $delivery_data['iid'] = $current_post;
1793 self::insertDeliveryData($delivery_data);
1798 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1799 * This is not perfect - but a workable solution until we found the reason for the problem.
1801 if (!empty($tags)) {
1802 Term::insertFromTagFieldByItemId($current_post, $tags);
1805 if (!empty($files)) {
1806 Term::insertFromFileFieldByItemId($current_post, $files);
1809 if ($item['parent-uri'] === $item['uri']) {
1810 self::addShadow($current_post);
1812 self::addShadowPost($current_post);
1815 check_user_notification($current_post);
1818 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1819 } elseif (!empty($parent) && $parent['origin']) {
1820 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1823 return $current_post;
1827 * @brief Insert a new item delivery data entry
1829 * @param array $item The item fields that are to be inserted
1831 private static function insertDeliveryData($delivery_data)
1833 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1837 DBA::insert('item-delivery-data', $delivery_data);
1841 * @brief Update an existing item delivery data entry
1843 * @param integer $id The item id that is to be updated
1844 * @param array $item The item fields that are to be inserted
1846 private static function updateDeliveryData($id, $delivery_data)
1848 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1852 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1856 * @brief Insert a new item content entry
1858 * @param array $item The item fields that are to be inserted
1860 private static function insertActivity(&$item)
1862 $activity_index = self::activityToIndex($item['verb']);
1864 if ($activity_index < 0) {
1868 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1869 'uri-hash' => $item['uri-hash']];
1871 // We just remove everything that is content
1872 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1873 unset($item[$field]);
1876 // To avoid timing problems, we are using locks.
1877 $locked = Lock::acquire('item_insert_activity');
1879 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1882 // Do we already have this content?
1883 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1884 if (DBA::isResult($item_activity)) {
1885 $item['iaid'] = $item_activity['id'];
1886 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1887 } elseif (DBA::insert('item-activity', $fields)) {
1888 $item['iaid'] = DBA::lastInsertId();
1889 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1891 // This shouldn't happen.
1892 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1896 Lock::release('item_insert_activity');
1902 * @brief Insert a new item content entry
1904 * @param array $item The item fields that are to be inserted
1906 private static function insertContent(&$item)
1908 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1910 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1911 if (isset($item[$field])) {
1912 $fields[$field] = $item[$field];
1913 unset($item[$field]);
1917 // To avoid timing problems, we are using locks.
1918 $locked = Lock::acquire('item_insert_content');
1920 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1923 // Do we already have this content?
1924 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1925 if (DBA::isResult($item_content)) {
1926 $item['icid'] = $item_content['id'];
1927 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1928 } elseif (DBA::insert('item-content', $fields)) {
1929 $item['icid'] = DBA::lastInsertId();
1930 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1932 // This shouldn't happen.
1933 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1936 Lock::release('item_insert_content');
1941 * @brief Update existing item content entries
1943 * @param array $item The item fields that are to be changed
1944 * @param array $condition The condition for finding the item content entries
1946 private static function updateActivity($item, $condition)
1948 if (empty($item['verb'])) {
1951 $activity_index = self::activityToIndex($item['verb']);
1953 if ($activity_index < 0) {
1957 $fields = ['activity' => $activity_index];
1959 logger('Update activity for ' . json_encode($condition));
1961 DBA::update('item-activity', $fields, $condition, true);
1967 * @brief Update existing item content entries
1969 * @param array $item The item fields that are to be changed
1970 * @param array $condition The condition for finding the item content entries
1972 private static function updateContent($item, $condition)
1974 // We have to select only the fields from the "item-content" table
1976 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1977 if (isset($item[$field])) {
1978 $fields[$field] = $item[$field];
1982 if (empty($fields)) {
1983 // when there are no fields at all, just use the condition
1984 // This is to ensure that we always store content.
1985 $fields = $condition;
1988 logger('Update content for ' . json_encode($condition));
1990 DBA::update('item-content', $fields, $condition, true);
1994 * @brief Distributes public items to the receivers
1996 * @param integer $itemid Item ID that should be added
1997 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1999 public static function distribute($itemid, $signed_text = '')
2001 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2002 $parent = self::selectFirst(['owner-id'], $condition);
2003 if (!DBA::isResult($parent)) {
2007 // Only distribute public items from native networks
2008 $condition = ['id' => $itemid, 'uid' => 0,
2009 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2010 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2011 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2012 if (!DBA::isResult($item)) {
2016 $origin = $item['origin'];
2019 unset($item['parent']);
2020 unset($item['mention']);
2021 unset($item['wall']);
2022 unset($item['origin']);
2023 unset($item['starred']);
2027 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2028 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
2029 $contacts = DBA::select('contact', ['uid'], $condition);
2030 while ($contact = DBA::fetch($contacts)) {
2031 $users[$contact['uid']] = $contact['uid'];
2036 if ($item['uri'] != $item['parent-uri']) {
2037 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2038 while ($parent = DBA::fetch($parents)) {
2039 $users[$parent['uid']] = $parent['uid'];
2040 if ($parent['origin'] && !$origin) {
2041 $origin_uid = $parent['uid'];
2046 foreach ($users as $uid) {
2047 if ($origin_uid == $uid) {
2048 $item['diaspora_signed_text'] = $signed_text;
2050 self::storeForUser($itemid, $item, $uid);
2055 * @brief Store public items for the receivers
2057 * @param integer $itemid Item ID that should be added
2058 * @param array $item The item entry that will be stored
2059 * @param integer $uid The user that will receive the item entry
2061 private static function storeForUser($itemid, $item, $uid)
2063 $item['uid'] = $uid;
2064 $item['origin'] = 0;
2066 if ($item['uri'] == $item['parent-uri']) {
2067 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2069 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2072 if (empty($item['contact-id'])) {
2073 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2074 if (!DBA::isResult($self)) {
2077 $item['contact-id'] = $self['id'];
2080 /// @todo Handling of "event-id"
2083 if ($item['uri'] == $item['parent-uri']) {
2084 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2085 if (DBA::isResult($contact)) {
2086 $notify = self::isRemoteSelf($contact, $item);
2090 $distributed = self::insert($item, false, $notify, true);
2092 if (!$distributed) {
2093 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2095 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2100 * @brief Add a shadow entry for a given item id that is a thread starter
2102 * We store every public item entry additionally with the user id "0".
2103 * This is used for the community page and for the search.
2104 * It is planned that in the future we will store public item entries only once.
2106 * @param integer $itemid Item ID that should be added
2108 public static function addShadow($itemid)
2110 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2111 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2112 $item = self::selectFirst($fields, $condition);
2114 if (!DBA::isResult($item)) {
2118 // is it already a copy?
2119 if (($itemid == 0) || ($item['uid'] == 0)) {
2123 // Is it a visible public post?
2124 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2128 // is it an entry from a connector? Only add an entry for natively connected networks
2129 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2133 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2137 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2139 if (DBA::isResult($item)) {
2140 // Preparing public shadow (removing user specific data)
2143 unset($item['parent']);
2144 unset($item['wall']);
2145 unset($item['mention']);
2146 unset($item['origin']);
2147 unset($item['starred']);
2148 unset($item['postopts']);
2149 unset($item['inform']);
2150 if ($item['uri'] == $item['parent-uri']) {
2151 $item['contact-id'] = $item['owner-id'];
2153 $item['contact-id'] = $item['author-id'];
2156 $public_shadow = self::insert($item, false, false, true);
2158 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2163 * @brief Add a shadow entry for a given item id that is a comment
2165 * This function does the same like the function above - but for comments
2167 * @param integer $itemid Item ID that should be added
2169 public static function addShadowPost($itemid)
2171 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2172 if (!DBA::isResult($item)) {
2176 // Is it a toplevel post?
2177 if ($item['id'] == $item['parent']) {
2178 self::addShadow($itemid);
2182 // Is this a shadow entry?
2183 if ($item['uid'] == 0) {
2187 // Is there a shadow parent?
2188 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2192 // Is there already a shadow entry?
2193 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2197 // Save "origin" and "parent" state
2198 $origin = $item['origin'];
2199 $parent = $item['parent'];
2201 // Preparing public shadow (removing user specific data)
2204 unset($item['parent']);
2205 unset($item['wall']);
2206 unset($item['mention']);
2207 unset($item['origin']);
2208 unset($item['starred']);
2209 unset($item['postopts']);
2210 unset($item['inform']);
2211 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2213 $public_shadow = self::insert($item, false, false, true);
2215 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2217 // If this was a comment to a Diaspora post we don't get our comment back.
2218 // This means that we have to distribute the comment by ourselves.
2219 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2220 self::distribute($public_shadow);
2225 * Adds a language specification in a "language" element of given $arr.
2226 * Expects "body" element to exist in $arr.
2228 private static function addLanguageToItemArray(&$item)
2230 // @TODO Find out why body can be empty here
2231 $item['body'] = defaults($item, 'body', '');
2233 $naked_body = BBCode::toPlaintext($item['body'], false);
2235 $ld = new Text_LanguageDetect();
2236 $ld->setNameMode(2);
2237 $languages = $ld->detect($naked_body, 3);
2239 if (is_array($languages)) {
2240 $item['language'] = json_encode($languages);
2245 * @brief Creates an unique guid out of a given uri
2247 * @param string $uri uri of an item entry
2248 * @param string $host hostname for the GUID prefix
2249 * @return string unique guid
2251 public static function guidFromUri($uri, $host)
2253 // Our regular guid routine is using this kind of prefix as well
2254 // We have to avoid that different routines could accidentally create the same value
2255 $parsed = parse_url($uri);
2257 // We use a hash of the hostname as prefix for the guid
2258 $guid_prefix = hash("crc32", $host);
2260 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2261 unset($parsed["scheme"]);
2263 // Glue it together to be able to make a hash from it
2264 $host_id = implode("/", $parsed);
2266 // We could use any hash algorithm since it isn't a security issue
2267 $host_hash = hash("ripemd128", $host_id);
2269 return $guid_prefix.$host_hash;
2273 * generate an unique URI
2275 * @param integer $uid User id
2276 * @param string $guid An existing GUID (Otherwise it will be generated)
2280 public static function newURI($uid, $guid = "")
2283 $guid = System::createGUID(32);
2286 $hostname = self::getApp()->get_hostname();
2288 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2290 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2296 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2298 * This can be used to filter for inactive contacts.
2299 * Only do this for public postings to avoid privacy problems, since poco data is public.
2300 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2302 * @param array $arr Contains the just posted item record
2304 private static function updateContact($arr)
2306 // Unarchive the author
2307 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2308 if (DBA::isResult($contact)) {
2309 Contact::unmarkForArchival($contact);
2312 // Unarchive the contact if it's not our own contact
2313 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2314 if (DBA::isResult($contact)) {
2315 Contact::unmarkForArchival($contact);
2318 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2320 // Is it a forum? Then we don't care about the rules from above
2321 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2322 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2328 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2329 ['id' => $arr['contact-id']]);
2331 // Now do the same for the system wide contacts with uid=0
2332 if (!$arr['private']) {
2333 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2334 ['id' => $arr['owner-id']]);
2336 if ($arr['owner-id'] != $arr['author-id']) {
2337 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2338 ['id' => $arr['author-id']]);
2343 public static function setHashtags(&$item)
2346 $tags = get_tags($item["body"]);
2349 if (!count($tags)) {
2353 // This sorting is important when there are hashtags that are part of other hashtags
2354 // Otherwise there could be problems with hashtags like #test and #test2
2357 $URLSearchString = "^\[\]";
2359 // All hashtags should point to the home server if "local_tags" is activated
2360 if (Config::get('system', 'local_tags')) {
2361 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2362 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2364 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2365 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2368 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2369 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2371 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2374 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2376 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2379 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2381 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2384 // Repair recursive urls
2385 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2386 "#$2", $item["body"]);
2388 foreach ($tags as $tag) {
2389 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2393 $basetag = str_replace('_',' ',substr($tag,1));
2395 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2397 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2399 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2400 if (strlen($item["tag"])) {
2401 $item["tag"] = ','.$item["tag"];
2403 $item["tag"] = $newtag.$item["tag"];
2407 // Convert back the masked hashtags
2408 $item["body"] = str_replace("#", "#", $item["body"]);
2411 public static function getGuidById($id)
2413 $item = self::selectFirst(['guid'], ['id' => $id]);
2414 if (DBA::isResult($item)) {
2415 return $item['guid'];
2421 public static function getIdAndNickByGuid($guid, $uid = 0)
2427 $uid == local_user();
2430 // Does the given user have this item?
2432 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2433 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2434 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2435 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2436 if (DBA::isResult($item)) {
2438 $nick = $item["nickname"];
2442 // Or is it anywhere on the server?
2444 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2445 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2446 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2447 AND NOT `item`.`private` AND `item`.`wall`
2448 AND `item`.`guid` = ?", $guid);
2449 if (DBA::isResult($item)) {
2451 $nick = $item["nickname"];
2454 return ["nick" => $nick, "id" => $id];
2458 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2460 * @param int $item_id
2461 * @return bool true if item was deleted, else false
2463 private static function tagDeliver($uid, $item_id)
2467 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2468 if (!DBA::isResult($user)) {
2472 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2473 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2475 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2476 if (!DBA::isResult($item)) {
2480 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2483 * Diaspora uses their own hardwired link URL in @-tags
2484 * instead of the one we supply with webfinger
2486 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2488 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2490 foreach ($matches as $mtch) {
2491 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2493 logger('mention found: ' . $mtch[2]);
2499 if (($community_page || $prvgroup) &&
2500 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2501 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2503 logger("no-mention top-level post to community or private group. delete.");
2504 DBA::delete('item', ['id' => $item_id]);
2510 $arr = ['item' => $item, 'user' => $user];
2512 Addon::callHooks('tagged', $arr);
2514 if (!$community_page && !$prvgroup) {
2519 * tgroup delivery - setup a second delivery chain
2520 * prevent delivery looping - only proceed
2521 * if the message originated elsewhere and is a top-level post
2523 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2527 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2528 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2529 if (!DBA::isResult($self)) {
2533 $owner_id = Contact::getIdForURL($self['url']);
2535 // also reset all the privacy bits to the forum default permissions
2537 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2539 $forum_mode = ($prvgroup ? 2 : 1);
2541 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2542 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2543 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2544 DBA::update('item', $fields, ['id' => $item_id]);
2546 self::updateThread($item_id);
2548 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2551 public static function isRemoteSelf($contact, &$datarray)
2555 if (!$contact['remote_self']) {
2559 // Prevent the forwarding of posts that are forwarded
2560 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2561 logger('Already forwarded', LOGGER_DEBUG);
2565 // Prevent to forward already forwarded posts
2566 if ($datarray["app"] == $a->get_hostname()) {
2567 logger('Already forwarded (second test)', LOGGER_DEBUG);
2571 // Only forward posts
2572 if ($datarray["verb"] != ACTIVITY_POST) {
2573 logger('No post', LOGGER_DEBUG);
2577 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2578 logger('Not public', LOGGER_DEBUG);
2582 $datarray2 = $datarray;
2583 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2584 if ($contact['remote_self'] == 2) {
2585 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2586 ['uid' => $contact['uid'], 'self' => true]);
2587 if (DBA::isResult($self)) {
2588 $datarray['contact-id'] = $self["id"];
2590 $datarray['owner-name'] = $self["name"];
2591 $datarray['owner-link'] = $self["url"];
2592 $datarray['owner-avatar'] = $self["thumb"];
2594 $datarray['author-name'] = $datarray['owner-name'];
2595 $datarray['author-link'] = $datarray['owner-link'];
2596 $datarray['author-avatar'] = $datarray['owner-avatar'];
2598 unset($datarray['created']);
2599 unset($datarray['edited']);
2601 unset($datarray['network']);
2602 unset($datarray['owner-id']);
2603 unset($datarray['author-id']);
2606 if ($contact['network'] != NETWORK_FEED) {
2607 $datarray["guid"] = System::createGUID(32);
2608 unset($datarray["plink"]);
2609 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2610 $datarray["parent-uri"] = $datarray["uri"];
2611 $datarray["thr-parent"] = $datarray["uri"];
2612 $datarray["extid"] = NETWORK_DFRN;
2613 $urlpart = parse_url($datarray2['author-link']);
2614 $datarray["app"] = $urlpart["host"];
2616 $datarray['private'] = 0;
2620 if ($contact['network'] != NETWORK_FEED) {
2621 // Store the original post
2622 $result = self::insert($datarray2, false, false);
2623 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2625 $datarray["app"] = "Feed";
2629 // Trigger automatic reactions for addons
2630 $datarray['api_source'] = true;
2632 // We have to tell the hooks who we are - this really should be improved
2633 $_SESSION["authenticated"] = true;
2634 $_SESSION["uid"] = $contact['uid'];
2643 * @param array $item
2647 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2649 if (Config::get('system', 'disable_embedded')) {
2653 logger('check for photos', LOGGER_DEBUG);
2654 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2659 $img_start = strpos($orig_body, '[img');
2660 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2661 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2663 while (($img_st_close !== false) && ($img_len !== false)) {
2664 $img_st_close++; // make it point to AFTER the closing bracket
2665 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2667 logger('found photo ' . $image, LOGGER_DEBUG);
2669 if (stristr($image, $site . '/photo/')) {
2670 // Only embed locally hosted photos
2672 $i = basename($image);
2673 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2674 $x = strpos($i, '-');
2677 $res = substr($i, $x + 1);
2678 $i = substr($i, 0, $x);
2679 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2680 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2681 if (DBA::isResult($photo)) {
2683 * Check to see if we should replace this photo link with an embedded image
2684 * 1. No need to do so if the photo is public
2685 * 2. If there's a contact-id provided, see if they're in the access list
2686 * for the photo. If so, embed it.
2687 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2688 * permissions, regardless of order but first check to see if they're an exact
2689 * match to save some processing overhead.
2691 if (self::hasPermissions($photo)) {
2693 $recips = self::enumeratePermissions($photo);
2694 if (in_array($cid, $recips)) {
2698 if (self::samePermissions($item, $photo)) {
2704 $data = $photo['data'];
2705 $type = $photo['type'];
2707 // If a custom width and height were specified, apply before embedding
2708 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2709 logger('scaling photo', LOGGER_DEBUG);
2711 $width = intval($match[1]);
2712 $height = intval($match[2]);
2714 $Image = new Image($data, $type);
2715 if ($Image->isValid()) {
2716 $Image->scaleDown(max($width, $height));
2717 $data = $Image->asString();
2718 $type = $Image->getType();
2722 logger('replacing photo', LOGGER_DEBUG);
2723 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2724 logger('replaced: ' . $image, LOGGER_DATA);
2730 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2731 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2732 if ($orig_body === false) {
2736 $img_start = strpos($orig_body, '[img');
2737 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2738 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2741 $new_body = $new_body . $orig_body;
2746 private static function hasPermissions($obj)
2748 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2749 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2752 private static function samePermissions($obj1, $obj2)
2754 // first part is easy. Check that these are exactly the same.
2755 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2756 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2757 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2758 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2762 // This is harder. Parse all the permissions and compare the resulting set.
2763 $recipients1 = self::enumeratePermissions($obj1);
2764 $recipients2 = self::enumeratePermissions($obj2);
2768 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2769 return ($recipients1 == $recipients2);
2772 // returns an array of contact-ids that are allowed to see this object
2773 private static function enumeratePermissions($obj)
2775 $allow_people = expand_acl($obj['allow_cid']);
2776 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2777 $deny_people = expand_acl($obj['deny_cid']);
2778 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2779 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2780 $deny = array_unique(array_merge($deny_people, $deny_groups));
2781 $recipients = array_diff($recipients, $deny);
2785 public static function getFeedTags($item)
2789 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2791 for ($x = 0; $x < $cnt; $x ++) {
2792 if ($matches[1][$x]) {
2793 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2798 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2800 for ($x = 0; $x < $cnt; $x ++) {
2801 if ($matches[1][$x]) {
2802 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2809 public static function expire($uid, $days, $network = "", $force = false)
2811 if (!$uid || ($days < 1)) {
2815 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2816 $uid, GRAVITY_PARENT];
2819 * $expire_network_only = save your own wall posts
2820 * and just expire conversations started by others
2822 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2824 if ($expire_network_only) {
2825 $condition[0] .= " AND NOT `wall`";
2828 if ($network != "") {
2829 $condition[0] .= " AND `network` = ?";
2830 $condition[] = $network;
2833 * There is an index "uid_network_received" but not "uid_network_created"
2834 * This avoids the creation of another index just for one purpose.
2835 * And it doesn't really matter wether to look at "received" or "created"
2837 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2838 $condition[] = $days;
2840 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2841 $condition[] = $days;
2844 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2846 if (!DBA::isResult($items)) {
2850 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2852 // Forcing expiring of items - but not notes and marked items
2854 $expire_items = true;
2857 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2858 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2859 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2863 while ($item = Item::fetch($items)) {
2864 // don't expire filed items
2866 if (strpos($item['file'], '[') !== false) {
2870 // Only expire posts, not photos and photo comments
2872 if (!$expire_photos && strlen($item['resource-id'])) {
2874 } elseif (!$expire_starred && intval($item['starred'])) {
2876 } elseif (!$expire_notes && $item['type'] == 'note') {
2878 } elseif (!$expire_items && $item['type'] != 'note') {
2882 self::deleteById($item['id'], PRIORITY_LOW);
2887 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2890 public static function firstPostDate($uid, $wall = false)
2892 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2893 $params = ['order' => ['created' => false]];
2894 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2895 if (DBA::isResult($thread)) {
2896 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2902 * @brief add/remove activity to an item
2904 * Toggle activities as like,dislike,attend of an item
2906 * @param string $item_id
2907 * @param string $verb
2908 * Activity verb. One of
2909 * like, unlike, dislike, undislike, attendyes, unattendyes,
2910 * attendno, unattendno, attendmaybe, unattendmaybe
2911 * @hook 'post_local_end'
2913 * 'post_id' => ID of posted item
2915 public static function performLike($item_id, $verb)
2917 if (!local_user() && !remote_user()) {
2924 $activity = ACTIVITY_LIKE;
2928 $activity = ACTIVITY_DISLIKE;
2932 $activity = ACTIVITY_ATTEND;
2936 $activity = ACTIVITY_ATTENDNO;
2939 case 'unattendmaybe':
2940 $activity = ACTIVITY_ATTENDMAYBE;
2943 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2947 // Enable activity toggling instead of on/off
2948 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2950 logger('like: verb ' . $verb . ' item ' . $item_id);
2952 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2953 if (!DBA::isResult($item)) {
2954 logger('like: unknown item ' . $item_id);
2958 $item_uri = $item['uri'];
2960 $uid = $item['uid'];
2961 if (($uid == 0) && local_user()) {
2962 $uid = local_user();
2965 if (!can_write_wall($uid)) {
2966 logger('like: unable to write on wall ' . $uid);
2970 // Retrieves the local post owner
2971 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2972 if (!DBA::isResult($owner_self_contact)) {
2973 logger('like: unknown owner ' . $uid);
2977 // Retrieve the current logged in user's public contact
2978 $author_id = public_contact();
2980 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
2981 if (!DBA::isResult($author_contact)) {
2982 logger('like: unknown author ' . $author_id);
2986 // Contact-id is the uid-dependant author contact
2987 if (local_user() == $uid) {
2988 $item_contact_id = $owner_self_contact['id'];
2989 $item_contact = $owner_self_contact;
2991 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2992 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
2993 if (!DBA::isResult($item_contact)) {
2994 logger('like: unknown item contact ' . $item_contact_id);
2999 // Look for an existing verb row
3000 // event participation are essentially radio toggles. If you make a subsequent choice,
3001 // we need to eradicate your first choice.
3002 if ($event_verb_flag) {
3003 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3005 // Translate to the index based activity index
3007 foreach ($verbs as $verb) {
3008 $activities[] = self::activityToIndex($verb);
3011 $activities = self::activityToIndex($activity);
3014 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3015 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3017 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3019 // If it exists, mark it as deleted
3020 if (DBA::isResult($like_item)) {
3021 // Already voted, undo it
3022 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
3023 /// @todo Consider using self::update - but before doing so, check the side effects
3024 DBA::update('item', $fields, ['id' => $like_item['id']]);
3026 // Clean up the Diaspora signatures for this like
3027 DBA::delete('sign', ['iid' => $like_item['id']]);
3029 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
3031 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3036 // Verb is "un-something", just trying to delete existing entries
3037 if (strpos($verb, 'un') === 0) {
3041 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3044 'guid' => System::createGUID(32),
3045 'uri' => self::newURI($item['uid']),
3046 'uid' => $item['uid'],
3047 'contact-id' => $item_contact_id,
3048 'wall' => $item['wall'],
3050 'network' => NETWORK_DFRN,
3051 'gravity' => GRAVITY_ACTIVITY,
3052 'parent' => $item['id'],
3053 'parent-uri' => $item['uri'],
3054 'thr-parent' => $item['uri'],
3055 'owner-id' => $item['owner-id'],
3056 'author-id' => $author_id,
3057 'body' => $activity,
3058 'verb' => $activity,
3059 'object-type' => $objtype,
3060 'allow_cid' => $item['allow_cid'],
3061 'allow_gid' => $item['allow_gid'],
3062 'deny_cid' => $item['deny_cid'],
3063 'deny_gid' => $item['deny_gid'],
3068 $new_item_id = self::insert($new_item);
3070 // If the parent item isn't visible then set it to visible
3071 if (!$item['visible']) {
3072 self::update(['visible' => true], ['id' => $item['id']]);
3075 // Save the author information for the like in case we need to relay to Diaspora
3076 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3078 $new_item['id'] = $new_item_id;
3080 Addon::callHooks('post_local_end', $new_item);
3082 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3087 private static function addThread($itemid, $onlyshadow = false)
3089 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3090 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3091 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3092 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3093 $item = self::selectFirst($fields, $condition);
3095 if (!DBA::isResult($item)) {
3099 $item['iid'] = $itemid;
3102 $result = DBA::insert('thread', $item);
3104 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3108 private static function updateThread($itemid, $setmention = false)
3110 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3111 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3112 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3113 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3115 $item = self::selectFirst($fields, $condition);
3116 if (!DBA::isResult($item)) {
3121 $item["mention"] = 1;
3128 foreach ($item as $field => $data) {
3129 if (!in_array($field, ["guid"])) {
3130 $fields[$field] = $data;
3134 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3136 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3139 private static function deleteThread($itemid, $itemuri = "")
3141 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3142 if (!DBA::isResult($item)) {
3143 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3147 // Using dba::delete at this time could delete the associated item entries
3148 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3150 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3152 if ($itemuri != "") {
3153 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3154 if (!self::exists($condition)) {
3155 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3156 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);