4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\Lock;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\PermissionSet;
20 use Friendica\Model\ItemURI;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\XML;
26 use Text_LanguageDetect;
28 require_once 'boot.php';
29 require_once 'include/items.php';
30 require_once 'include/text.php';
32 class Item extends BaseObject
34 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
41 const PT_DOCUMENT = 19;
43 const PT_PERSONAL_NOTE = 128;
45 // Field list that is used to display the items
46 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
47 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
48 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
49 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
50 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
51 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
52 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
53 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
54 'writable', 'self', 'cid', 'alias',
55 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
56 'event-summary', 'event-desc', 'event-location', 'event-type',
57 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
59 // Field list that is used to deliver items via the protocols
60 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
61 'created', 'edited', 'verb', 'object-type', 'object', 'target',
62 'private', 'title', 'body', 'location', 'coord', 'app',
63 'attach', 'tag', 'deleted', 'extid', 'post-type',
64 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
65 'author-id', 'author-link', 'owner-link', 'contact-uid',
66 'signed_text', 'signature', 'signer', 'network'];
68 // Field list for "item-content" table that is mixed with the item table
69 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
70 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
71 'object-type', 'object', 'target-type', 'target', 'plink'];
73 // Field list for "item-content" table that is not present in the "item" table
74 const CONTENT_FIELDLIST = ['language'];
76 // Field list for additional delivery data
77 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
79 // All fields in the item table
80 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
81 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
82 'created', 'edited', 'commented', 'received', 'changed', 'verb',
83 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
84 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
85 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
86 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
87 'title', 'content-warning', 'body', 'location', 'coord', 'app',
88 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
89 'author-id', 'author-link', 'author-name', 'author-avatar',
90 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
92 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
93 // The item-activity table only stores the index and needs this array to know the matching activity.
94 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
96 private static $legacy_mode = null;
98 public static function isLegacyMode()
100 if (is_null(self::$legacy_mode)) {
101 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
104 return self::$legacy_mode;
108 * @brief returns an activity index from an activity string
110 * @param string $activity activity string
111 * @return integer Activity index
113 private static function activityToIndex($activity)
115 $index = array_search($activity, self::ACTIVITIES);
117 if (is_bool($index)) {
125 * @brief returns an activity string from an activity index
127 * @param integer $index activity index
128 * @return string Activity string
130 private static function indexToActivity($index)
132 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
136 return self::ACTIVITIES[$index];
140 * @brief Fetch a single item row
142 * @param mixed $stmt statement object
143 * @return array current row
145 public static function fetch($stmt)
147 $row = DBA::fetch($stmt);
153 // ---------------------- Transform item structure data ----------------------
155 // We prefer the data from the user's contact over the public one
156 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
157 ($row['author-link'] == $row['contact-link'])) {
158 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
159 $row['author-avatar'] = $row['contact-avatar'];
161 if (isset($row['author-name']) && !empty($row['contact-name'])) {
162 $row['author-name'] = $row['contact-name'];
166 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
167 ($row['owner-link'] == $row['contact-link'])) {
168 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
169 $row['owner-avatar'] = $row['contact-avatar'];
171 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
172 $row['owner-name'] = $row['contact-name'];
176 // We can always comment on posts from these networks
177 if (array_key_exists('writable', $row) &&
178 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
179 $row['writable'] = true;
182 // ---------------------- Transform item content data ----------------------
184 // Fetch data from the item-content table whenever there is content there
185 if (self::isLegacyMode()) {
186 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
187 foreach ($legacy_fields as $field) {
188 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
189 $row[$field] = $row['internal-item-' . $field];
191 unset($row['internal-item-' . $field]);
195 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
196 $row['verb'] = self::indexToActivity($row['internal-activity']);
197 if (array_key_exists('title', $row)) {
200 if (array_key_exists('body', $row)) {
201 $row['body'] = $row['verb'];
203 if (array_key_exists('object', $row)) {
206 if (array_key_exists('object-type', $row)) {
207 $row['object-type'] = ACTIVITY_OBJ_NOTE;
209 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
210 // Posts don't have an object or target - but having tags or files.
211 // We safe some performance by building tag and file strings only here.
212 // We remove object and target since they aren't used for this type.
213 if (array_key_exists('object', $row)) {
216 if (array_key_exists('target', $row)) {
221 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
222 // Build the tag string out of the term entries
223 if (array_key_exists('tag', $row) && empty($row['tag'])) {
224 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
227 // Build the file string out of the term entries
228 if (array_key_exists('file', $row) && empty($row['file'])) {
229 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
233 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
234 $row['ignored'] = $row['internal-user-ignored'];
237 // Remove internal fields
238 unset($row['internal-activity']);
239 unset($row['internal-network']);
240 unset($row['internal-iid']);
241 unset($row['internal-iaid']);
242 unset($row['internal-icid']);
243 unset($row['internal-user-ignored']);
249 * @brief Fills an array with data from an item query
251 * @param object $stmt statement object
252 * @return array Data array
254 public static function inArray($stmt, $do_close = true) {
255 if (is_bool($stmt)) {
260 while ($row = self::fetch($stmt)) {
270 * @brief Check if item data exists
272 * @param array $condition array of fields for condition
274 * @return boolean Are there rows for that condition?
276 public static function exists($condition) {
277 $stmt = self::select(['id'], $condition, ['limit' => 1]);
279 if (is_bool($stmt)) {
282 $retval = (DBA::numRows($stmt) > 0);
291 * Retrieve a single record from the item table for a given user and returns it in an associative array
293 * @brief Retrieve a single record from a table
294 * @param integer $uid User ID
295 * @param array $fields
296 * @param array $condition
297 * @param array $params
301 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
303 $params['uid'] = $uid;
305 if (empty($selected)) {
306 $selected = Item::DISPLAY_FIELDLIST;
309 return self::selectFirst($selected, $condition, $params);
313 * @brief Select rows from the item table for a given user
315 * @param integer $uid User ID
316 * @param array $selected Array of selected fields, empty for all
317 * @param array $condition Array of fields for condition
318 * @param array $params Array of several parameters
320 * @return boolean|object
322 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
324 $params['uid'] = $uid;
326 if (empty($selected)) {
327 $selected = Item::DISPLAY_FIELDLIST;
330 return self::select($selected, $condition, $params);
334 * Retrieve a single record from the item table and returns it in an associative array
336 * @brief Retrieve a single record from a table
337 * @param array $fields
338 * @param array $condition
339 * @param array $params
343 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
345 $params['limit'] = 1;
347 $result = self::select($fields, $condition, $params);
349 if (is_bool($result)) {
352 $row = self::fetch($result);
359 * @brief Select rows from the item table
361 * @param array $selected Array of selected fields, empty for all
362 * @param array $condition Array of fields for condition
363 * @param array $params Array of several parameters
365 * @return boolean|object
367 public static function select(array $selected = [], array $condition = [], $params = [])
372 if (isset($params['uid'])) {
373 $uid = $params['uid'];
377 $fields = self::fieldlist($selected, $usermode);
379 $select_fields = self::constructSelectFields($fields, $selected);
381 $condition_string = DBA::buildCondition($condition);
383 $condition_string = self::addTablesToFields($condition_string, $fields);
386 $condition_string = $condition_string . ' AND ' . self::condition(false);
389 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
391 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
393 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
395 return DBA::p($sql, $condition);
399 * @brief Select rows from the starting post in the item table
401 * @param integer $uid User ID
402 * @param array $fields Array of selected fields, empty for all
403 * @param array $condition Array of fields for condition
404 * @param array $params Array of several parameters
406 * @return boolean|object
408 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
410 $params['uid'] = $uid;
412 if (empty($selected)) {
413 $selected = Item::DISPLAY_FIELDLIST;
416 return self::selectThread($selected, $condition, $params);
420 * Retrieve a single record from the starting post in the item table and returns it in an associative array
422 * @brief Retrieve a single record from a table
423 * @param integer $uid User ID
424 * @param array $selected
425 * @param array $condition
426 * @param array $params
430 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
432 $params['uid'] = $uid;
434 if (empty($selected)) {
435 $selected = Item::DISPLAY_FIELDLIST;
438 return self::selectFirstThread($selected, $condition, $params);
442 * Retrieve a single record from the starting post in the item table and returns it in an associative array
444 * @brief Retrieve a single record from a table
445 * @param array $fields
446 * @param array $condition
447 * @param array $params
451 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
453 $params['limit'] = 1;
454 $result = self::selectThread($fields, $condition, $params);
456 if (is_bool($result)) {
459 $row = self::fetch($result);
466 * @brief Select rows from the starting post in the item table
468 * @param array $selected Array of selected fields, empty for all
469 * @param array $condition Array of fields for condition
470 * @param array $params Array of several parameters
472 * @return boolean|object
474 public static function selectThread(array $selected = [], array $condition = [], $params = [])
479 if (isset($params['uid'])) {
480 $uid = $params['uid'];
484 $fields = self::fieldlist($selected, $usermode);
486 $fields['thread'] = ['mention', 'ignored', 'iid'];
488 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
489 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
490 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
491 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
493 $select_fields = self::constructSelectFields($fields, $selected);
495 $condition_string = DBA::buildCondition($condition);
497 $condition_string = self::addTablesToFields($condition_string, $threadfields);
498 $condition_string = self::addTablesToFields($condition_string, $fields);
501 $condition_string = $condition_string . ' AND ' . self::condition(true);
504 $param_string = DBA::buildParameter($params);
505 $param_string = self::addTablesToFields($param_string, $threadfields);
506 $param_string = self::addTablesToFields($param_string, $fields);
508 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
510 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
512 return DBA::p($sql, $condition);
516 * @brief Returns a list of fields that are associated with the item table
518 * @return array field list
520 private static function fieldlist($selected, $usermode)
524 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
525 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
526 'created', 'edited', 'commented', 'received', 'changed', 'psid',
527 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
528 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
529 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
530 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
531 'network' => 'internal-network', 'icid' => 'internal-icid',
532 'iaid' => 'internal-iaid'];
535 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
538 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
540 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
542 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
544 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
546 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
547 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
549 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
550 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
552 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
553 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
554 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
556 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
558 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
560 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
561 'start' => 'event-start','finish' => 'event-finish',
562 'summary' => 'event-summary','desc' => 'event-desc',
563 'location' => 'event-location', 'type' => 'event-type',
564 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
565 'ignore' => 'event-ignore', 'id' => 'event-id'];
567 $fields['sign'] = ['signed_text', 'signature', 'signer'];
573 * @brief Returns SQL condition for the "select" functions
575 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
577 * @return string SQL condition
579 private static function condition($thread_mode)
582 $master_table = "`thread`";
584 $master_table = "`item`";
586 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`) ";
590 * @brief Returns all needed "JOIN" commands for the "select" functions
592 * @param integer $uid User ID
593 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
594 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
596 * @return string The SQL joins for the "select" functions
598 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
601 $master_table = "`thread`";
602 $master_table_key = "`thread`.`iid`";
603 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
605 $master_table = "`item`";
606 $master_table_key = "`item`.`id`";
611 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
612 AND NOT `contact`.`blocked`
613 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
614 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
615 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
616 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
617 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
618 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid));
620 if (strpos($sql_commands, "`contact`.") !== false) {
621 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
623 if (strpos($sql_commands, "`author`.") !== false) {
624 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
626 if (strpos($sql_commands, "`owner`.") !== false) {
627 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
631 if (strpos($sql_commands, "`group_member`.") !== false) {
632 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
635 if (strpos($sql_commands, "`user`.") !== false) {
636 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
639 if (strpos($sql_commands, "`event`.") !== false) {
640 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
643 if (strpos($sql_commands, "`sign`.") !== false) {
644 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
647 if (strpos($sql_commands, "`item-activity`.") !== false) {
648 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
651 if (strpos($sql_commands, "`item-content`.") !== false) {
652 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
655 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
656 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
659 if (strpos($sql_commands, "`permissionset`.") !== false) {
660 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
663 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
664 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
667 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
668 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
675 * @brief Add the field list for the "select" functions
677 * @param array $fields The field definition array
678 * @param array $selected The array with the selected fields from the "select" functions
680 * @return string The field list
682 private static function constructSelectFields($fields, $selected)
684 if (!empty($selected)) {
685 $selected[] = 'internal-iid';
686 $selected[] = 'internal-iaid';
687 $selected[] = 'internal-icid';
688 $selected[] = 'internal-network';
691 if (in_array('verb', $selected)) {
692 $selected[] = 'internal-activity';
695 if (in_array('ignored', $selected)) {
696 $selected[] = 'internal-user-ignored';
700 foreach ($fields as $table => $table_fields) {
701 foreach ($table_fields as $field => $select) {
702 if (empty($selected) || in_array($select, $selected)) {
703 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
704 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
705 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
707 if (is_int($field)) {
708 $selection[] = "`" . $table . "`.`" . $select . "`";
710 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
715 return implode(", ", $selection);
719 * @brief add table definition to fields in an SQL query
721 * @param string $query SQL query
722 * @param array $fields The field definition array
724 * @return string the changed SQL query
726 private static function addTablesToFields($query, $fields)
728 foreach ($fields as $table => $table_fields) {
729 foreach ($table_fields as $alias => $field) {
730 if (is_int($alias)) {
731 $replace_field = $field;
733 $replace_field = $alias;
736 $search = "/([^\.])`" . $field . "`/i";
737 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
738 $query = preg_replace($search, $replace, $query);
745 * @brief Generate a server unique item hash for linking between the item tables
747 * @param string $uri Item URI
748 * @param date $created Item creation date
750 * @return string the item hash
752 private static function itemHash($uri, $created)
754 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
758 * @brief Update existing item entries
760 * @param array $fields The fields that are to be changed
761 * @param array $condition The condition for finding the item entries
763 * In the future we may have to change permissions as well.
764 * Then we had to add the user id as third parameter.
766 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
768 * @return integer|boolean number of affected rows - or "false" if there was an error
770 public static function update(array $fields, array $condition)
772 if (empty($condition) || empty($fields)) {
776 // To ensure the data integrity we do it in an transaction
779 // We cannot simply expand the condition to check for origin entries
780 // The condition needn't to be a simple array but could be a complex condition.
781 // And we have to execute this query before the update to ensure to fetch the same data.
782 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
784 $content_fields = [];
785 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
786 if (isset($fields[$field])) {
787 $content_fields[$field] = $fields[$field];
788 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
789 unset($fields[$field]);
791 $fields[$field] = null;
796 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
797 foreach ($clear_fields as $field) {
798 if (array_key_exists($field, $fields)) {
799 $fields[$field] = null;
803 if (array_key_exists('tag', $fields)) {
804 $tags = $fields['tag'];
805 $fields['tag'] = null;
810 if (array_key_exists('file', $fields)) {
811 $files = $fields['file'];
812 $fields['file'] = null;
817 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
818 'inform' => defaults($fields, 'inform', '')];
820 $fields['postopts'] = null;
821 $fields['inform'] = null;
823 if (!empty($fields)) {
824 $success = DBA::update('item', $fields, $condition);
833 // When there is no content for the "old" item table, this will count the fetched items
834 $rows = DBA::affectedRows();
836 while ($item = DBA::fetch($items)) {
838 // This part here can safely be removed when the legacy fields in the item had been removed
839 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
841 // Fetch the uri-hash from an existing item entry if there is one
842 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
843 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
844 if (DBA::isResult($existing)) {
845 $item['uri-hash'] = $existing['uri-hash'];
847 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
850 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
851 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
852 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
855 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
856 if (!empty($item['iaid'])) {
857 $update_condition = ['id' => $item['iaid']];
859 $update_condition = ['uri-hash' => $item['uri-hash']];
861 self::updateActivity($content_fields, $update_condition);
863 if (empty($item['iaid'])) {
864 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
865 if (DBA::isResult($item_activity)) {
866 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
867 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
868 if (self::isLegacyMode()) {
869 $item_fields[$field] = null;
871 unset($item_fields[$field]);
874 DBA::update('item', $item_fields, ['id' => $item['id']]);
876 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
877 DBA::delete('item-content', ['id' => $item['icid']]);
880 } elseif (!empty($item['icid'])) {
881 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
883 if (!DBA::exists('item', ['icid' => $item['icid']])) {
884 DBA::delete('item-content', ['id' => $item['icid']]);
888 if (!empty($item['icid'])) {
889 $update_condition = ['id' => $item['icid']];
891 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
893 self::updateContent($content_fields, $update_condition);
895 if (empty($item['icid'])) {
896 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
897 if (DBA::isResult($item_content)) {
898 $item_fields = ['icid' => $item_content['id']];
899 // Clear all fields in the item table that have a content in the item-content table
900 foreach ($item_content as $field => $content) {
901 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
902 if (self::isLegacyMode()) {
903 $item_fields[$field] = null;
905 unset($item_fields[$field]);
909 DBA::update('item', $item_fields, ['id' => $item['id']]);
915 Term::insertFromTagFieldByItemId($item['id'], $tags);
916 if (!empty($item['tag'])) {
917 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
921 if (!empty($files)) {
922 Term::insertFromFileFieldByItemId($item['id'], $files);
923 if (!empty($item['file'])) {
924 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
928 self::updateDeliveryData($item['id'], $delivery_data);
930 self::updateThread($item['id']);
932 // We only need to notfiy others when it is an original entry from us.
933 // Only call the notifier when the item has some content relevant change.
934 if ($item['origin'] && in_array('edited', array_keys($fields))) {
935 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
945 * @brief Delete an item and notify others about it - if it was ours
947 * @param array $condition The condition for finding the item entries
948 * @param integer $priority Priority for the notification
950 public static function delete($condition, $priority = PRIORITY_HIGH)
952 $items = DBA::select('item', ['id'], $condition);
953 while ($item = DBA::fetch($items)) {
954 self::deleteById($item['id'], $priority);
960 * @brief Delete an item for an user and notify others about it - if it was ours
962 * @param array $condition The condition for finding the item entries
963 * @param integer $uid User who wants to delete this item
965 public static function deleteForUser($condition, $uid)
971 $items = DBA::select('item', ['id', 'uid'], $condition);
972 while ($item = DBA::fetch($items)) {
973 // "Deleting" global items just means hiding them
974 if ($item['uid'] == 0) {
975 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
976 } elseif ($item['uid'] == $uid) {
977 self::deleteById($item['id'], PRIORITY_HIGH);
979 logger('Wrong ownership. Not deleting item ' . $item['id']);
986 * @brief Delete an item and notify others about it - if it was ours
988 * @param integer $item_id Item ID that should be delete
989 * @param integer $priority Priority for the notification
991 * @return boolean success
993 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
995 // locate item to be deleted
996 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
997 'deleted', 'file', 'resource-id', 'event-id', 'attach',
998 'verb', 'object-type', 'object', 'target', 'contact-id',
999 'icid', 'iaid', 'psid'];
1000 $item = self::selectFirst($fields, ['id' => $item_id]);
1001 if (!DBA::isResult($item)) {
1002 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
1006 if ($item['deleted']) {
1007 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
1011 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1012 if (!DBA::isResult($parent)) {
1013 $parent = ['origin' => false];
1016 // clean up categories and tags so they don't end up as orphans
1019 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1021 foreach ($matches as $mtch) {
1022 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1028 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1030 foreach ($matches as $mtch) {
1031 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1036 * If item is a link to a photo resource, nuke all the associated photos
1037 * (visitors will not have photo resources)
1038 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1039 * generate a resource-id and therefore aren't intimately linked to the item.
1041 if (strlen($item['resource-id'])) {
1042 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1045 // If item is a link to an event, delete the event.
1046 if (intval($item['event-id'])) {
1047 Event::delete($item['event-id']);
1050 // If item has attachments, drop them
1051 foreach (explode(", ", $item['attach']) as $attach) {
1052 preg_match("|attach/(\d+)|", $attach, $matches);
1053 if (is_array($matches) && count($matches) > 1) {
1054 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1058 // Delete tags that had been attached to other items
1059 self::deleteTagsFromItem($item);
1061 // Set the item to "deleted"
1062 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1063 DBA::update('item', $item_fields, ['id' => $item['id']]);
1065 Term::insertFromTagFieldByItemId($item['id'], '');
1066 Term::insertFromFileFieldByItemId($item['id'], '');
1067 self::deleteThread($item['id'], $item['parent-uri']);
1069 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1070 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1073 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1075 if (!empty($item['iaid']) && !DBA::exists('item', ['iaid' => $item['iaid'], 'deleted' => false])) {
1076 DBA::delete('item-activity', ['id' => $item['iaid']], ['cascade' => false]);
1078 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid'], 'deleted' => false])) {
1079 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1081 // When the permission set will be used in photo and events as well,
1082 // this query here needs to be extended.
1083 if (!empty($item['psid']) && !DBA::exists('item', ['psid' => $item['psid'], 'deleted' => false])) {
1084 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1087 // If it's the parent of a comment thread, kill all the kids
1088 if ($item['id'] == $item['parent']) {
1089 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1092 // Is it our comment and/or our thread?
1093 if ($item['origin'] || $parent['origin']) {
1095 // When we delete the original post we will delete all existing copies on the server as well
1096 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1098 // send the notification upstream/downstream
1099 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1100 } elseif ($item['uid'] != 0) {
1102 // When we delete just our local user copy of an item, we have to set a marker to hide it
1103 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1104 if (DBA::isResult($global_item)) {
1105 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1109 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1114 private static function deleteTagsFromItem($item)
1116 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1120 $xo = XML::parseString($item["object"], false);
1121 $xt = XML::parseString($item["target"], false);
1123 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1127 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1128 if (!DBA::isResult($i)) {
1132 // For tags, the owner cannot remove the tag on the author's copy of the post.
1133 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1134 $author_copy = $item["origin"];
1136 if (($owner_remove && $author_copy) || !$owner_remove) {
1140 $tags = explode(',', $i["tag"]);
1143 foreach ($tags as $tag) {
1144 if (trim($tag) !== trim($xo->body)) {
1145 $newtags[] = trim($tag);
1149 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1152 private static function guid($item, $notify)
1154 if (!empty($item['guid'])) {
1155 return notags(trim($item['guid']));
1159 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1160 // We add the hash of our own host because our host is the original creator of the post.
1161 $prefix_host = get_app()->get_hostname();
1165 // We are only storing the post so we create a GUID from the original hostname.
1166 if (!empty($item['author-link'])) {
1167 $parsed = parse_url($item['author-link']);
1168 if (!empty($parsed['host'])) {
1169 $prefix_host = $parsed['host'];
1173 if (empty($prefix_host) && !empty($item['plink'])) {
1174 $parsed = parse_url($item['plink']);
1175 if (!empty($parsed['host'])) {
1176 $prefix_host = $parsed['host'];
1180 if (empty($prefix_host) && !empty($item['uri'])) {
1181 $parsed = parse_url($item['uri']);
1182 if (!empty($parsed['host'])) {
1183 $prefix_host = $parsed['host'];
1187 // Is it in the format data@host.tld? - Used for mail contacts
1188 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1189 $mailparts = explode('@', $item['author-link']);
1190 $prefix_host = array_pop($mailparts);
1194 if (!empty($item['plink'])) {
1195 $guid = self::guidFromUri($item['plink'], $prefix_host);
1196 } elseif (!empty($item['uri'])) {
1197 $guid = self::guidFromUri($item['uri'], $prefix_host);
1199 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1205 private static function contactId($item)
1207 $contact_id = (int)$item["contact-id"];
1209 if (!empty($contact_id)) {
1212 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1214 * First we are looking for a suitable contact that matches with the author of the post
1215 * This is done only for comments
1217 if ($item['parent-uri'] != $item['uri']) {
1218 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1221 // If not present then maybe the owner was found
1222 if ($contact_id == 0) {
1223 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1226 // Still missing? Then use the "self" contact of the current user
1227 if ($contact_id == 0) {
1228 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1229 if (DBA::isResult($self)) {
1230 $contact_id = $self["id"];
1233 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1238 // This function will finally cover most of the preparation functionality in mod/item.php
1239 public static function prepare(&$item)
1241 $data = BBCode::getAttachmentData($item['body']);
1242 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1243 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1244 $posttype = Item::PT_PAGE;
1245 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1249 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1253 // If it is a posting where users should get notifications, then define it as wall posting
1256 $item['origin'] = 1;
1257 $item['network'] = NETWORK_DFRN;
1258 $item['protocol'] = Conversation::PARCEL_DFRN;
1260 if (is_int($notify)) {
1261 $priority = $notify;
1263 $priority = PRIORITY_HIGH;
1266 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1269 $item['guid'] = self::guid($item, $notify);
1270 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1273 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1275 // Store conversation data
1276 $item = Conversation::insert($item);
1279 * If a Diaspora signature structure was passed in, pull it out of the
1280 * item array and set it aside for later storage.
1284 if (x($item, 'dsprsig')) {
1285 $encoded_signature = $item['dsprsig'];
1286 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1287 unset($item['dsprsig']);
1290 if (!empty($item['diaspora_signed_text'])) {
1291 $diaspora_signed_text = $item['diaspora_signed_text'];
1292 unset($item['diaspora_signed_text']);
1294 $diaspora_signed_text = '';
1297 // Converting the plink
1298 /// @TODO Check if this is really still needed
1299 if ($item['network'] == NETWORK_OSTATUS) {
1300 if (isset($item['plink'])) {
1301 $item['plink'] = OStatus::convertHref($item['plink']);
1302 } elseif (isset($item['uri'])) {
1303 $item['plink'] = OStatus::convertHref($item['uri']);
1307 if (!empty($item['thr-parent'])) {
1308 $item['parent-uri'] = $item['thr-parent'];
1311 if (isset($item['gravity'])) {
1312 $item['gravity'] = intval($item['gravity']);
1313 } elseif ($item['parent-uri'] === $item['uri']) {
1314 $item['gravity'] = GRAVITY_PARENT;
1315 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1316 $item['gravity'] = GRAVITY_COMMENT;
1318 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1319 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1322 $uid = intval($item['uid']);
1324 // check for create date and expire time
1325 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1327 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1328 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1329 $expire_interval = $user['expire'];
1332 if (($expire_interval > 0) && !empty($item['created'])) {
1333 $expire_date = time() - ($expire_interval * 86400);
1334 $created_date = strtotime($item['created']);
1335 if ($created_date < $expire_date) {
1336 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1342 * Do we already have this item?
1343 * We have to check several networks since Friendica posts could be repeated
1344 * via OStatus (maybe Diasporsa as well)
1346 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1347 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1348 trim($item['uri']), $item['uid'],
1349 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1350 $existing = self::selectFirst(['id', 'network'], $condition);
1351 if (DBA::isResult($existing)) {
1352 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1354 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1357 return $existing["id"];
1361 // Ensure to always have the same creation date.
1362 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1363 if (DBA::isResult($existing)) {
1364 $item['created'] = $existing['created'];
1365 $item['uri-hash'] = $existing['uri-hash'];
1368 $item['wall'] = intval(defaults($item, 'wall', 0));
1369 $item['extid'] = trim(defaults($item, 'extid', ''));
1370 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1371 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1372 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1373 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1374 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1375 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1376 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1377 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1378 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1379 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1380 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1381 $item['title'] = trim(defaults($item, 'title', ''));
1382 $item['location'] = trim(defaults($item, 'location', ''));
1383 $item['coord'] = trim(defaults($item, 'coord', ''));
1384 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1385 $item['deleted'] = 0;
1386 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1387 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1388 $item['verb'] = trim(defaults($item, 'verb', ''));
1389 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1390 $item['object'] = trim(defaults($item, 'object', ''));
1391 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1392 $item['target'] = trim(defaults($item, 'target', ''));
1393 $item['plink'] = trim(defaults($item, 'plink', ''));
1394 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1395 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1396 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1397 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1398 $item['private'] = intval(defaults($item, 'private', 0));
1399 $item['body'] = trim(defaults($item, 'body', ''));
1400 $item['tag'] = trim(defaults($item, 'tag', ''));
1401 $item['attach'] = trim(defaults($item, 'attach', ''));
1402 $item['app'] = trim(defaults($item, 'app', ''));
1403 $item['origin'] = intval(defaults($item, 'origin', 0));
1404 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1405 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1406 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1407 $item['inform'] = trim(defaults($item, 'inform', ''));
1408 $item['file'] = trim(defaults($item, 'file', ''));
1410 // Unique identifier to be linked against item-activities and item-content
1411 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1413 // When there is no content then we don't post it
1414 if ($item['body'].$item['title'] == '') {
1415 logger('No body, no title.');
1419 self::addLanguageToItemArray($item);
1421 // Items cannot be stored before they happen ...
1422 if ($item['created'] > DateTimeFormat::utcNow()) {
1423 $item['created'] = DateTimeFormat::utcNow();
1426 // We haven't invented time travel by now.
1427 if ($item['edited'] > DateTimeFormat::utcNow()) {
1428 $item['edited'] = DateTimeFormat::utcNow();
1431 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1433 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1434 $item["contact-id"] = self::contactId($item);
1436 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1437 'photo' => $item['author-avatar'], 'network' => $item['network']];
1439 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1441 if (Contact::isBlocked($item["author-id"])) {
1442 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1446 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1447 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1449 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1451 if (Contact::isBlocked($item["owner-id"])) {
1452 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1456 // These fields aren't stored anymore in the item table, they are fetched upon request
1457 unset($item['author-link']);
1458 unset($item['author-name']);
1459 unset($item['author-avatar']);
1461 unset($item['owner-link']);
1462 unset($item['owner-name']);
1463 unset($item['owner-avatar']);
1465 if ($item['network'] == NETWORK_PHANTOM) {
1466 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1468 $item['network'] = NETWORK_DFRN;
1469 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1472 // Checking if there is already an item with the same guid
1473 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1474 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1475 if (self::exists($condition)) {
1476 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1480 // Check for hashtags in the body and repair or add hashtag links
1481 self::setHashtags($item);
1483 $item['thr-parent'] = $item['parent-uri'];
1491 if ($item['parent-uri'] === $item['uri']) {
1493 $parent_deleted = 0;
1494 $allow_cid = $item['allow_cid'];
1495 $allow_gid = $item['allow_gid'];
1496 $deny_cid = $item['deny_cid'];
1497 $deny_gid = $item['deny_gid'];
1498 $notify_type = 'wall-new';
1500 // find the parent and snarf the item id and ACLs
1501 // and anything else we need to inherit
1503 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1504 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1505 'wall', 'private', 'forum_mode', 'origin'];
1506 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1507 $params = ['order' => ['id' => false]];
1508 $parent = self::selectFirst($fields, $condition, $params);
1510 if (DBA::isResult($parent)) {
1511 // is the new message multi-level threaded?
1512 // even though we don't support it now, preserve the info
1513 // and re-attach to the conversation parent.
1515 if ($parent['uri'] != $parent['parent-uri']) {
1516 $item['parent-uri'] = $parent['parent-uri'];
1518 $condition = ['uri' => $item['parent-uri'],
1519 'parent-uri' => $item['parent-uri'],
1520 'uid' => $item['uid']];
1521 $params = ['order' => ['id' => false]];
1522 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1524 if (DBA::isResult($toplevel_parent)) {
1525 $parent = $toplevel_parent;
1529 $parent_id = $parent['id'];
1530 $parent_deleted = $parent['deleted'];
1531 $allow_cid = $parent['allow_cid'];
1532 $allow_gid = $parent['allow_gid'];
1533 $deny_cid = $parent['deny_cid'];
1534 $deny_gid = $parent['deny_gid'];
1535 $item['wall'] = $parent['wall'];
1536 $notify_type = 'comment-new';
1539 * If the parent is private, force privacy for the entire conversation
1540 * This differs from the above settings as it subtly allows comments from
1541 * email correspondents to be private even if the overall thread is not.
1543 if ($parent['private']) {
1544 $item['private'] = $parent['private'];
1548 * Edge case. We host a public forum that was originally posted to privately.
1549 * The original author commented, but as this is a comment, the permissions
1550 * weren't fixed up so it will still show the comment as private unless we fix it here.
1552 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1553 $item['private'] = 0;
1556 // If its a post from myself then tag the thread as "mention"
1557 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1558 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1559 if (DBA::isResult($user)) {
1560 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1561 $self_id = Contact::getIdForURL($self, 0, true);
1562 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1563 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1564 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1565 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1570 * Allow one to see reply tweets from status.net even when
1571 * we don't have or can't see the original post.
1573 if ($force_parent) {
1574 logger('$force_parent=true, reply converted to top-level post.');
1576 $item['parent-uri'] = $item['uri'];
1577 $item['gravity'] = GRAVITY_PARENT;
1579 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1583 $parent_deleted = 0;
1587 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1588 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1590 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1591 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1592 if (self::exists($condition)) {
1593 logger('duplicated item with the same uri found. '.print_r($item,true));
1597 // On Friendica and Diaspora the GUID is unique
1598 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1599 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1600 if (self::exists($condition)) {
1601 logger('duplicated item with the same guid found. '.print_r($item,true));
1605 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1606 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1607 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1608 if (self::exists($condition)) {
1609 logger('duplicated item with the same body found. '.print_r($item,true));
1614 // Is this item available in the global items (with uid=0)?
1615 if ($item["uid"] == 0) {
1616 $item["global"] = true;
1618 // Set the global flag on all items if this was a global item entry
1619 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1621 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1625 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1628 $private = $item['private'];
1631 $item["allow_cid"] = $allow_cid;
1632 $item["allow_gid"] = $allow_gid;
1633 $item["deny_cid"] = $deny_cid;
1634 $item["deny_gid"] = $deny_gid;
1635 $item["private"] = $private;
1636 $item["deleted"] = $parent_deleted;
1638 // Fill the cache field
1639 put_item_in_cache($item);
1642 $item['edit'] = false;
1643 $item['parent'] = $parent_id;
1644 Addon::callHooks('post_local', $item);
1645 unset($item['edit']);
1646 unset($item['parent']);
1648 Addon::callHooks('post_remote', $item);
1651 // This array field is used to trigger some automatic reactions
1652 // It is mainly used in the "post_local" hook.
1653 unset($item['api_source']);
1655 if (x($item, 'cancel')) {
1656 logger('post cancelled by addon.');
1661 * Check for already added items.
1662 * There is a timing issue here that sometimes creates double postings.
1663 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1665 if ($item["uid"] == 0) {
1666 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1667 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1672 logger('' . print_r($item,true), LOGGER_DATA);
1674 if (array_key_exists('tag', $item)) {
1675 $tags = $item['tag'];
1676 unset($item['tag']);
1681 if (array_key_exists('file', $item)) {
1682 $files = $item['file'];
1683 unset($item['file']);
1688 // Creates or assigns the permission set
1689 $item['psid'] = PermissionSet::fetchIDForPost($item);
1691 // We are doing this outside of the transaction to avoid timing problems
1692 if (!self::insertActivity($item)) {
1693 self::insertContent($item);
1696 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1697 'inform' => defaults($item, 'inform', '')];
1699 unset($item['postopts']);
1700 unset($item['inform']);
1703 $ret = DBA::insert('item', $item);
1705 // When the item was successfully stored we fetch the ID of the item.
1706 if (DBA::isResult($ret)) {
1707 $current_post = DBA::lastInsertId();
1709 // This can happen - for example - if there are locking timeouts.
1712 // Store the data into a spool file so that we can try again later.
1714 // At first we restore the Diaspora signature that we removed above.
1715 if (isset($encoded_signature)) {
1716 $item['dsprsig'] = $encoded_signature;
1719 // Now we store the data in the spool directory
1720 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1721 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1723 $spoolpath = get_spoolpath();
1724 if ($spoolpath != "") {
1725 $spool = $spoolpath.'/'.$file;
1727 // Ensure to have the removed data from above again in the item array
1728 $item = array_merge($item, $delivery_data);
1730 file_put_contents($spool, json_encode($item));
1731 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1736 if ($current_post == 0) {
1737 // This is one of these error messages that never should occur.
1738 logger("couldn't find created item - we better quit now.");
1743 // How much entries have we created?
1744 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1745 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1748 // There are duplicates. We delete our just created entry.
1749 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1751 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1752 DBA::delete('item', ['id' => $current_post]);
1755 } elseif ($entries == 0) {
1756 // This really should never happen since we quit earlier if there were problems.
1757 logger("Something is terribly wrong. We haven't found our created entry.");
1762 logger('created item '.$current_post);
1763 self::updateContact($item);
1765 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1766 $parent_id = $current_post;
1770 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1772 $item['id'] = $current_post;
1773 $item['parent'] = $parent_id;
1775 // update the commented timestamp on the parent
1776 // Only update "commented" if it is really a comment
1777 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1778 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1780 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1785 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1786 * We can check for this condition when we decode and encode the stuff again.
1788 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1789 $dsprsig->signature = base64_decode($dsprsig->signature);
1790 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1793 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1794 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1797 if (!empty($diaspora_signed_text)) {
1798 // Formerly we stored the signed text, the signature and the author in different fields.
1799 // We now store the raw data so that we are more flexible.
1800 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1803 $deleted = self::tagDeliver($item['uid'], $current_post);
1806 * current post can be deleted if is for a community page and no mention are
1809 if (!$deleted && !$dontcache) {
1810 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1811 if (DBA::isResult($posted_item)) {
1813 Addon::callHooks('post_local_end', $posted_item);
1815 Addon::callHooks('post_remote_end', $posted_item);
1818 logger('new item not found in DB, id ' . $current_post);
1822 if ($item['parent-uri'] === $item['uri']) {
1823 self::addThread($current_post);
1825 self::updateThread($parent_id);
1828 $delivery_data['iid'] = $current_post;
1830 self::insertDeliveryData($delivery_data);
1835 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1836 * This is not perfect - but a workable solution until we found the reason for the problem.
1838 if (!empty($tags)) {
1839 Term::insertFromTagFieldByItemId($current_post, $tags);
1842 if (!empty($files)) {
1843 Term::insertFromFileFieldByItemId($current_post, $files);
1846 if ($item['parent-uri'] === $item['uri']) {
1847 self::addShadow($current_post);
1849 self::addShadowPost($current_post);
1852 check_user_notification($current_post);
1855 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1856 } elseif (!empty($parent) && $parent['origin']) {
1857 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1860 return $current_post;
1864 * @brief Insert a new item delivery data entry
1866 * @param array $item The item fields that are to be inserted
1868 private static function insertDeliveryData($delivery_data)
1870 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1874 DBA::insert('item-delivery-data', $delivery_data);
1878 * @brief Update an existing item delivery data entry
1880 * @param integer $id The item id that is to be updated
1881 * @param array $item The item fields that are to be inserted
1883 private static function updateDeliveryData($id, $delivery_data)
1885 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1889 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1893 * @brief Insert a new item content entry
1895 * @param array $item The item fields that are to be inserted
1897 private static function insertActivity(&$item)
1899 $activity_index = self::activityToIndex($item['verb']);
1901 if ($activity_index < 0) {
1905 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1906 'uri-hash' => $item['uri-hash'], 'uri-id' => $item['uri-id']];
1908 // We just remove everything that is content
1909 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1910 unset($item[$field]);
1913 // To avoid timing problems, we are using locks.
1914 $locked = Lock::acquire('item_insert_activity');
1916 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1919 // Do we already have this content?
1920 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1921 if (DBA::isResult($item_activity)) {
1922 $item['iaid'] = $item_activity['id'];
1923 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1924 } elseif (DBA::insert('item-activity', $fields)) {
1925 $item['iaid'] = DBA::lastInsertId();
1926 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1928 // This shouldn't happen.
1929 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1933 Lock::release('item_insert_activity');
1939 * @brief Insert a new item content entry
1941 * @param array $item The item fields that are to be inserted
1943 private static function insertContent(&$item)
1945 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash'],
1946 'uri-id' => $item['uri-id']];
1948 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1949 if (isset($item[$field])) {
1950 $fields[$field] = $item[$field];
1951 unset($item[$field]);
1955 // To avoid timing problems, we are using locks.
1956 $locked = Lock::acquire('item_insert_content');
1958 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1961 // Do we already have this content?
1962 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1963 if (DBA::isResult($item_content)) {
1964 $item['icid'] = $item_content['id'];
1965 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1966 } elseif (DBA::insert('item-content', $fields)) {
1967 $item['icid'] = DBA::lastInsertId();
1968 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1970 // This shouldn't happen.
1971 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1974 Lock::release('item_insert_content');
1979 * @brief Update existing item content entries
1981 * @param array $item The item fields that are to be changed
1982 * @param array $condition The condition for finding the item content entries
1984 private static function updateActivity($item, $condition)
1986 if (empty($item['verb'])) {
1989 $activity_index = self::activityToIndex($item['verb']);
1991 if ($activity_index < 0) {
1995 $fields = ['activity' => $activity_index];
1997 logger('Update activity for ' . json_encode($condition));
1999 DBA::update('item-activity', $fields, $condition, true);
2005 * @brief Update existing item content entries
2007 * @param array $item The item fields that are to be changed
2008 * @param array $condition The condition for finding the item content entries
2010 private static function updateContent($item, $condition)
2012 // We have to select only the fields from the "item-content" table
2014 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2015 if (isset($item[$field])) {
2016 $fields[$field] = $item[$field];
2020 if (empty($fields)) {
2021 // when there are no fields at all, just use the condition
2022 // This is to ensure that we always store content.
2023 $fields = $condition;
2026 logger('Update content for ' . json_encode($condition));
2028 DBA::update('item-content', $fields, $condition, true);
2032 * @brief Distributes public items to the receivers
2034 * @param integer $itemid Item ID that should be added
2035 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2037 public static function distribute($itemid, $signed_text = '')
2039 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2040 $parent = self::selectFirst(['owner-id'], $condition);
2041 if (!DBA::isResult($parent)) {
2045 // Only distribute public items from native networks
2046 $condition = ['id' => $itemid, 'uid' => 0,
2047 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2048 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2049 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2050 if (!DBA::isResult($item)) {
2054 $origin = $item['origin'];
2057 unset($item['parent']);
2058 unset($item['mention']);
2059 unset($item['wall']);
2060 unset($item['origin']);
2061 unset($item['starred']);
2065 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2066 $parent['owner-id'], Contact::SHARING, Contact::FRIEND];
2068 $contacts = DBA::select('contact', ['uid'], $condition);
2070 while ($contact = DBA::fetch($contacts)) {
2071 $users[$contact['uid']] = $contact['uid'];
2076 if ($item['uri'] != $item['parent-uri']) {
2077 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2078 while ($parent = DBA::fetch($parents)) {
2079 $users[$parent['uid']] = $parent['uid'];
2080 if ($parent['origin'] && !$origin) {
2081 $origin_uid = $parent['uid'];
2086 foreach ($users as $uid) {
2087 if ($origin_uid == $uid) {
2088 $item['diaspora_signed_text'] = $signed_text;
2090 self::storeForUser($itemid, $item, $uid);
2095 * @brief Store public items for the receivers
2097 * @param integer $itemid Item ID that should be added
2098 * @param array $item The item entry that will be stored
2099 * @param integer $uid The user that will receive the item entry
2101 private static function storeForUser($itemid, $item, $uid)
2103 $item['uid'] = $uid;
2104 $item['origin'] = 0;
2106 if ($item['uri'] == $item['parent-uri']) {
2107 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2109 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2112 if (empty($item['contact-id'])) {
2113 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2114 if (!DBA::isResult($self)) {
2117 $item['contact-id'] = $self['id'];
2120 /// @todo Handling of "event-id"
2123 if ($item['uri'] == $item['parent-uri']) {
2124 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2125 if (DBA::isResult($contact)) {
2126 $notify = self::isRemoteSelf($contact, $item);
2130 $distributed = self::insert($item, false, $notify, true);
2132 if (!$distributed) {
2133 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2135 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2140 * @brief Add a shadow entry for a given item id that is a thread starter
2142 * We store every public item entry additionally with the user id "0".
2143 * This is used for the community page and for the search.
2144 * It is planned that in the future we will store public item entries only once.
2146 * @param integer $itemid Item ID that should be added
2148 public static function addShadow($itemid)
2150 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2151 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2152 $item = self::selectFirst($fields, $condition);
2154 if (!DBA::isResult($item)) {
2158 // is it already a copy?
2159 if (($itemid == 0) || ($item['uid'] == 0)) {
2163 // Is it a visible public post?
2164 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2168 // is it an entry from a connector? Only add an entry for natively connected networks
2169 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2173 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2177 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2179 if (DBA::isResult($item)) {
2180 // Preparing public shadow (removing user specific data)
2183 unset($item['parent']);
2184 unset($item['wall']);
2185 unset($item['mention']);
2186 unset($item['origin']);
2187 unset($item['starred']);
2188 unset($item['postopts']);
2189 unset($item['inform']);
2190 if ($item['uri'] == $item['parent-uri']) {
2191 $item['contact-id'] = $item['owner-id'];
2193 $item['contact-id'] = $item['author-id'];
2196 $public_shadow = self::insert($item, false, false, true);
2198 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2203 * @brief Add a shadow entry for a given item id that is a comment
2205 * This function does the same like the function above - but for comments
2207 * @param integer $itemid Item ID that should be added
2209 public static function addShadowPost($itemid)
2211 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2212 if (!DBA::isResult($item)) {
2216 // Is it a toplevel post?
2217 if ($item['id'] == $item['parent']) {
2218 self::addShadow($itemid);
2222 // Is this a shadow entry?
2223 if ($item['uid'] == 0) {
2227 // Is there a shadow parent?
2228 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2232 // Is there already a shadow entry?
2233 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2237 // Save "origin" and "parent" state
2238 $origin = $item['origin'];
2239 $parent = $item['parent'];
2241 // Preparing public shadow (removing user specific data)
2244 unset($item['parent']);
2245 unset($item['wall']);
2246 unset($item['mention']);
2247 unset($item['origin']);
2248 unset($item['starred']);
2249 unset($item['postopts']);
2250 unset($item['inform']);
2251 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2253 $public_shadow = self::insert($item, false, false, true);
2255 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2257 // If this was a comment to a Diaspora post we don't get our comment back.
2258 // This means that we have to distribute the comment by ourselves.
2259 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2260 self::distribute($public_shadow);
2265 * Adds a language specification in a "language" element of given $arr.
2266 * Expects "body" element to exist in $arr.
2268 private static function addLanguageToItemArray(&$item)
2270 $naked_body = BBCode::toPlaintext($item['body'], false);
2272 $ld = new Text_LanguageDetect();
2273 $ld->setNameMode(2);
2274 $languages = $ld->detect($naked_body, 3);
2276 if (is_array($languages)) {
2277 $item['language'] = json_encode($languages);
2282 * @brief Creates an unique guid out of a given uri
2284 * @param string $uri uri of an item entry
2285 * @param string $host hostname for the GUID prefix
2286 * @return string unique guid
2288 public static function guidFromUri($uri, $host)
2290 // Our regular guid routine is using this kind of prefix as well
2291 // We have to avoid that different routines could accidentally create the same value
2292 $parsed = parse_url($uri);
2294 // We use a hash of the hostname as prefix for the guid
2295 $guid_prefix = hash("crc32", $host);
2297 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2298 unset($parsed["scheme"]);
2300 // Glue it together to be able to make a hash from it
2301 $host_id = implode("/", $parsed);
2303 // We could use any hash algorithm since it isn't a security issue
2304 $host_hash = hash("ripemd128", $host_id);
2306 return $guid_prefix.$host_hash;
2310 * generate an unique URI
2312 * @param integer $uid User id
2313 * @param string $guid An existing GUID (Otherwise it will be generated)
2317 public static function newURI($uid, $guid = "")
2320 $guid = System::createGUID(32);
2323 $hostname = self::getApp()->get_hostname();
2325 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2327 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2333 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2335 * This can be used to filter for inactive contacts.
2336 * Only do this for public postings to avoid privacy problems, since poco data is public.
2337 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2339 * @param array $arr Contains the just posted item record
2341 private static function updateContact($arr)
2343 // Unarchive the author
2344 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2345 if (DBA::isResult($contact)) {
2346 Contact::unmarkForArchival($contact);
2349 // Unarchive the contact if it's not our own contact
2350 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2351 if (DBA::isResult($contact)) {
2352 Contact::unmarkForArchival($contact);
2355 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2357 // Is it a forum? Then we don't care about the rules from above
2358 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2359 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2365 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2366 ['id' => $arr['contact-id']]);
2368 // Now do the same for the system wide contacts with uid=0
2369 if (!$arr['private']) {
2370 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2371 ['id' => $arr['owner-id']]);
2373 if ($arr['owner-id'] != $arr['author-id']) {
2374 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2375 ['id' => $arr['author-id']]);
2380 public static function setHashtags(&$item)
2383 $tags = get_tags($item["body"]);
2386 if (!count($tags)) {
2390 // This sorting is important when there are hashtags that are part of other hashtags
2391 // Otherwise there could be problems with hashtags like #test and #test2
2394 $URLSearchString = "^\[\]";
2396 // All hashtags should point to the home server if "local_tags" is activated
2397 if (Config::get('system', 'local_tags')) {
2398 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2399 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2401 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2402 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2405 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2406 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2408 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2411 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2413 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2416 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2418 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2421 // Repair recursive urls
2422 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2423 "#$2", $item["body"]);
2425 foreach ($tags as $tag) {
2426 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2430 $basetag = str_replace('_',' ',substr($tag,1));
2432 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2434 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2436 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2437 if (strlen($item["tag"])) {
2438 $item["tag"] = ','.$item["tag"];
2440 $item["tag"] = $newtag.$item["tag"];
2444 // Convert back the masked hashtags
2445 $item["body"] = str_replace("#", "#", $item["body"]);
2448 public static function getGuidById($id)
2450 $item = self::selectFirst(['guid'], ['id' => $id]);
2451 if (DBA::isResult($item)) {
2452 return $item['guid'];
2458 public static function getIdAndNickByGuid($guid, $uid = 0)
2464 $uid == local_user();
2467 // Does the given user have this item?
2469 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2470 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2471 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2472 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2473 if (DBA::isResult($item)) {
2475 $nick = $item["nickname"];
2479 // Or is it anywhere on the server?
2481 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2482 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2483 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2484 AND NOT `item`.`private` AND `item`.`wall`
2485 AND `item`.`guid` = ?", $guid);
2486 if (DBA::isResult($item)) {
2488 $nick = $item["nickname"];
2491 return ["nick" => $nick, "id" => $id];
2495 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2497 * @param int $item_id
2498 * @return bool true if item was deleted, else false
2500 private static function tagDeliver($uid, $item_id)
2504 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2505 if (!DBA::isResult($user)) {
2509 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2510 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2512 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2513 if (!DBA::isResult($item)) {
2517 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2520 * Diaspora uses their own hardwired link URL in @-tags
2521 * instead of the one we supply with webfinger
2523 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2525 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2527 foreach ($matches as $mtch) {
2528 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2530 logger('mention found: ' . $mtch[2]);
2536 if (($community_page || $prvgroup) &&
2537 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2538 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2540 logger("no-mention top-level post to community or private group. delete.");
2541 DBA::delete('item', ['id' => $item_id]);
2547 $arr = ['item' => $item, 'user' => $user];
2549 Addon::callHooks('tagged', $arr);
2551 if (!$community_page && !$prvgroup) {
2556 * tgroup delivery - setup a second delivery chain
2557 * prevent delivery looping - only proceed
2558 * if the message originated elsewhere and is a top-level post
2560 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2564 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2565 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2566 if (!DBA::isResult($self)) {
2570 $owner_id = Contact::getIdForURL($self['url']);
2572 // also reset all the privacy bits to the forum default permissions
2574 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2576 $forum_mode = ($prvgroup ? 2 : 1);
2578 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2579 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2580 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2581 DBA::update('item', $fields, ['id' => $item_id]);
2583 self::updateThread($item_id);
2585 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2588 public static function isRemoteSelf($contact, &$datarray)
2592 if (!$contact['remote_self']) {
2596 // Prevent the forwarding of posts that are forwarded
2597 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2598 logger('Already forwarded', LOGGER_DEBUG);
2602 // Prevent to forward already forwarded posts
2603 if ($datarray["app"] == $a->get_hostname()) {
2604 logger('Already forwarded (second test)', LOGGER_DEBUG);
2608 // Only forward posts
2609 if ($datarray["verb"] != ACTIVITY_POST) {
2610 logger('No post', LOGGER_DEBUG);
2614 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2615 logger('Not public', LOGGER_DEBUG);
2619 $datarray2 = $datarray;
2620 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2621 if ($contact['remote_self'] == 2) {
2622 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2623 ['uid' => $contact['uid'], 'self' => true]);
2624 if (DBA::isResult($self)) {
2625 $datarray['contact-id'] = $self["id"];
2627 $datarray['owner-name'] = $self["name"];
2628 $datarray['owner-link'] = $self["url"];
2629 $datarray['owner-avatar'] = $self["thumb"];
2631 $datarray['author-name'] = $datarray['owner-name'];
2632 $datarray['author-link'] = $datarray['owner-link'];
2633 $datarray['author-avatar'] = $datarray['owner-avatar'];
2635 unset($datarray['created']);
2636 unset($datarray['edited']);
2638 unset($datarray['network']);
2639 unset($datarray['owner-id']);
2640 unset($datarray['author-id']);
2643 if ($contact['network'] != NETWORK_FEED) {
2644 $datarray["guid"] = System::createGUID(32);
2645 unset($datarray["plink"]);
2646 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2647 $datarray["parent-uri"] = $datarray["uri"];
2648 $datarray["thr-parent"] = $datarray["uri"];
2649 $datarray["extid"] = NETWORK_DFRN;
2650 $urlpart = parse_url($datarray2['author-link']);
2651 $datarray["app"] = $urlpart["host"];
2653 $datarray['private'] = 0;
2657 if ($contact['network'] != NETWORK_FEED) {
2658 // Store the original post
2659 $result = self::insert($datarray2, false, false);
2660 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2662 $datarray["app"] = "Feed";
2666 // Trigger automatic reactions for addons
2667 $datarray['api_source'] = true;
2669 // We have to tell the hooks who we are - this really should be improved
2670 $_SESSION["authenticated"] = true;
2671 $_SESSION["uid"] = $contact['uid'];
2680 * @param array $item
2684 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2686 if (Config::get('system', 'disable_embedded')) {
2690 logger('check for photos', LOGGER_DEBUG);
2691 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2696 $img_start = strpos($orig_body, '[img');
2697 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2698 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2700 while (($img_st_close !== false) && ($img_len !== false)) {
2701 $img_st_close++; // make it point to AFTER the closing bracket
2702 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2704 logger('found photo ' . $image, LOGGER_DEBUG);
2706 if (stristr($image, $site . '/photo/')) {
2707 // Only embed locally hosted photos
2709 $i = basename($image);
2710 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2711 $x = strpos($i, '-');
2714 $res = substr($i, $x + 1);
2715 $i = substr($i, 0, $x);
2716 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2717 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2718 if (DBA::isResult($photo)) {
2720 * Check to see if we should replace this photo link with an embedded image
2721 * 1. No need to do so if the photo is public
2722 * 2. If there's a contact-id provided, see if they're in the access list
2723 * for the photo. If so, embed it.
2724 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2725 * permissions, regardless of order but first check to see if they're an exact
2726 * match to save some processing overhead.
2728 if (self::hasPermissions($photo)) {
2730 $recips = self::enumeratePermissions($photo);
2731 if (in_array($cid, $recips)) {
2735 if (self::samePermissions($item, $photo)) {
2741 $data = $photo['data'];
2742 $type = $photo['type'];
2744 // If a custom width and height were specified, apply before embedding
2745 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2746 logger('scaling photo', LOGGER_DEBUG);
2748 $width = intval($match[1]);
2749 $height = intval($match[2]);
2751 $Image = new Image($data, $type);
2752 if ($Image->isValid()) {
2753 $Image->scaleDown(max($width, $height));
2754 $data = $Image->asString();
2755 $type = $Image->getType();
2759 logger('replacing photo', LOGGER_DEBUG);
2760 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2761 logger('replaced: ' . $image, LOGGER_DATA);
2767 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2768 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2769 if ($orig_body === false) {
2773 $img_start = strpos($orig_body, '[img');
2774 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2775 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2778 $new_body = $new_body . $orig_body;
2783 private static function hasPermissions($obj)
2785 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2786 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2789 private static function samePermissions($obj1, $obj2)
2791 // first part is easy. Check that these are exactly the same.
2792 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2793 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2794 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2795 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2799 // This is harder. Parse all the permissions and compare the resulting set.
2800 $recipients1 = self::enumeratePermissions($obj1);
2801 $recipients2 = self::enumeratePermissions($obj2);
2805 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2806 return ($recipients1 == $recipients2);
2809 // returns an array of contact-ids that are allowed to see this object
2810 private static function enumeratePermissions($obj)
2812 $allow_people = expand_acl($obj['allow_cid']);
2813 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2814 $deny_people = expand_acl($obj['deny_cid']);
2815 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2816 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2817 $deny = array_unique(array_merge($deny_people, $deny_groups));
2818 $recipients = array_diff($recipients, $deny);
2822 public static function getFeedTags($item)
2826 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2828 for ($x = 0; $x < $cnt; $x ++) {
2829 if ($matches[1][$x]) {
2830 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2835 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2837 for ($x = 0; $x < $cnt; $x ++) {
2838 if ($matches[1][$x]) {
2839 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2846 public static function expire($uid, $days, $network = "", $force = false)
2848 if (!$uid || ($days < 1)) {
2852 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2853 $uid, GRAVITY_PARENT];
2856 * $expire_network_only = save your own wall posts
2857 * and just expire conversations started by others
2859 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2861 if ($expire_network_only) {
2862 $condition[0] .= " AND NOT `wall`";
2865 if ($network != "") {
2866 $condition[0] .= " AND `network` = ?";
2867 $condition[] = $network;
2870 * There is an index "uid_network_received" but not "uid_network_created"
2871 * This avoids the creation of another index just for one purpose.
2872 * And it doesn't really matter wether to look at "received" or "created"
2874 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2875 $condition[] = $days;
2877 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2878 $condition[] = $days;
2881 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2883 if (!DBA::isResult($items)) {
2887 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2889 // Forcing expiring of items - but not notes and marked items
2891 $expire_items = true;
2894 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2895 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2896 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2900 while ($item = Item::fetch($items)) {
2901 // don't expire filed items
2903 if (strpos($item['file'], '[') !== false) {
2907 // Only expire posts, not photos and photo comments
2909 if (!$expire_photos && strlen($item['resource-id'])) {
2911 } elseif (!$expire_starred && intval($item['starred'])) {
2913 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2915 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2919 self::deleteById($item['id'], PRIORITY_LOW);
2924 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2927 public static function firstPostDate($uid, $wall = false)
2929 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2930 $params = ['order' => ['created' => false]];
2931 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2932 if (DBA::isResult($thread)) {
2933 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2939 * @brief add/remove activity to an item
2941 * Toggle activities as like,dislike,attend of an item
2943 * @param string $item_id
2944 * @param string $verb
2945 * Activity verb. One of
2946 * like, unlike, dislike, undislike, attendyes, unattendyes,
2947 * attendno, unattendno, attendmaybe, unattendmaybe
2948 * @hook 'post_local_end'
2950 * 'post_id' => ID of posted item
2952 public static function performLike($item_id, $verb)
2954 if (!local_user() && !remote_user()) {
2961 $activity = ACTIVITY_LIKE;
2965 $activity = ACTIVITY_DISLIKE;
2969 $activity = ACTIVITY_ATTEND;
2973 $activity = ACTIVITY_ATTENDNO;
2976 case 'unattendmaybe':
2977 $activity = ACTIVITY_ATTENDMAYBE;
2980 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2984 // Enable activity toggling instead of on/off
2985 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2987 logger('like: verb ' . $verb . ' item ' . $item_id);
2989 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2990 if (!DBA::isResult($item)) {
2991 logger('like: unknown item ' . $item_id);
2995 $item_uri = $item['uri'];
2997 $uid = $item['uid'];
2998 if (($uid == 0) && local_user()) {
2999 $uid = local_user();
3002 if (!can_write_wall($uid)) {
3003 logger('like: unable to write on wall ' . $uid);
3007 // Retrieves the local post owner
3008 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3009 if (!DBA::isResult($owner_self_contact)) {
3010 logger('like: unknown owner ' . $uid);
3014 // Retrieve the current logged in user's public contact
3015 $author_id = public_contact();
3017 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3018 if (!DBA::isResult($author_contact)) {
3019 logger('like: unknown author ' . $author_id);
3023 // Contact-id is the uid-dependant author contact
3024 if (local_user() == $uid) {
3025 $item_contact_id = $owner_self_contact['id'];
3026 $item_contact = $owner_self_contact;
3028 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3029 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3030 if (!DBA::isResult($item_contact)) {
3031 logger('like: unknown item contact ' . $item_contact_id);
3036 // Look for an existing verb row
3037 // event participation are essentially radio toggles. If you make a subsequent choice,
3038 // we need to eradicate your first choice.
3039 if ($event_verb_flag) {
3040 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3042 // Translate to the index based activity index
3044 foreach ($verbs as $verb) {
3045 $activities[] = self::activityToIndex($verb);
3048 $activities = self::activityToIndex($activity);
3051 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3052 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3054 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3056 // If it exists, mark it as deleted
3057 if (DBA::isResult($like_item)) {
3058 self::deleteById($like_item['id']);
3060 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3065 // Verb is "un-something", just trying to delete existing entries
3066 if (strpos($verb, 'un') === 0) {
3070 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3073 'guid' => System::createGUID(32),
3074 'uri' => self::newURI($item['uid']),
3075 'uid' => $item['uid'],
3076 'contact-id' => $item_contact_id,
3077 'wall' => $item['wall'],
3079 'network' => NETWORK_DFRN,
3080 'gravity' => GRAVITY_ACTIVITY,
3081 'parent' => $item['id'],
3082 'parent-uri' => $item['uri'],
3083 'thr-parent' => $item['uri'],
3084 'owner-id' => $item['owner-id'],
3085 'author-id' => $author_id,
3086 'body' => $activity,
3087 'verb' => $activity,
3088 'object-type' => $objtype,
3089 'allow_cid' => $item['allow_cid'],
3090 'allow_gid' => $item['allow_gid'],
3091 'deny_cid' => $item['deny_cid'],
3092 'deny_gid' => $item['deny_gid'],
3097 $new_item_id = self::insert($new_item);
3099 // If the parent item isn't visible then set it to visible
3100 if (!$item['visible']) {
3101 self::update(['visible' => true], ['id' => $item['id']]);
3104 // Save the author information for the like in case we need to relay to Diaspora
3105 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3107 $new_item['id'] = $new_item_id;
3109 Addon::callHooks('post_local_end', $new_item);
3111 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3116 private static function addThread($itemid, $onlyshadow = false)
3118 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3119 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3120 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3121 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3122 $item = self::selectFirst($fields, $condition);
3124 if (!DBA::isResult($item)) {
3128 $item['iid'] = $itemid;
3131 $result = DBA::insert('thread', $item);
3133 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3137 private static function updateThread($itemid, $setmention = false)
3139 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3140 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3141 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3142 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3144 $item = self::selectFirst($fields, $condition);
3145 if (!DBA::isResult($item)) {
3150 $item["mention"] = 1;
3157 foreach ($item as $field => $data) {
3158 if (!in_array($field, ["guid"])) {
3159 $fields[$field] = $data;
3163 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3165 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3168 private static function deleteThread($itemid, $itemuri = "")
3170 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3171 if (!DBA::isResult($item)) {
3172 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3176 // Using dba::delete at this time could delete the associated item entries
3177 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3179 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3181 if ($itemuri != "") {
3182 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3183 if (!self::exists($condition)) {
3184 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3185 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);