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\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\PermissionSet;
21 use Friendica\Model\ItemURI;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use Text_LanguageDetect;
29 require_once 'boot.php';
30 require_once 'include/items.php';
31 require_once 'include/text.php';
33 class Item extends BaseObject
35 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
42 const PT_DOCUMENT = 19;
44 const PT_PERSONAL_NOTE = 128;
46 // Field list that is used to display the items
47 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
48 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
49 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
50 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
51 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
52 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
53 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
54 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
55 'writable', 'self', 'cid', 'alias',
56 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
57 'event-summary', 'event-desc', 'event-location', 'event-type',
58 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
60 // Field list that is used to deliver items via the protocols
61 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
62 'created', 'edited', 'verb', 'object-type', 'object', 'target',
63 'private', 'title', 'body', 'location', 'coord', 'app',
64 'attach', 'tag', 'deleted', 'extid', 'post-type',
65 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
66 'author-id', 'author-link', 'owner-link', 'contact-uid',
67 'signed_text', 'signature', 'signer', 'network'];
69 // Field list for "item-content" table that is mixed with the item table
70 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
71 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
72 'object-type', 'object', 'target-type', 'target', 'plink'];
74 // Field list for "item-content" table that is not present in the "item" table
75 const CONTENT_FIELDLIST = ['language'];
77 // Field list for additional delivery data
78 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
80 // All fields in the item table
81 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
82 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
83 'created', 'edited', 'commented', 'received', 'changed', 'verb',
84 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
85 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
86 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
87 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
88 'title', 'content-warning', 'body', 'location', 'coord', 'app',
89 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
90 'author-id', 'author-link', 'author-name', 'author-avatar',
91 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
93 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
94 // The item-activity table only stores the index and needs this array to know the matching activity.
95 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
97 private static $legacy_mode = null;
99 public static function isLegacyMode()
101 if (is_null(self::$legacy_mode)) {
102 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
105 return self::$legacy_mode;
109 * @brief returns an activity index from an activity string
111 * @param string $activity activity string
112 * @return integer Activity index
114 public static function activityToIndex($activity)
116 $index = array_search($activity, self::ACTIVITIES);
118 if (is_bool($index)) {
126 * @brief returns an activity string from an activity index
128 * @param integer $index activity index
129 * @return string Activity string
131 private static function indexToActivity($index)
133 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
137 return self::ACTIVITIES[$index];
141 * @brief Fetch a single item row
143 * @param mixed $stmt statement object
144 * @return array current row
146 public static function fetch($stmt)
148 $row = DBA::fetch($stmt);
154 // ---------------------- Transform item structure data ----------------------
156 // We prefer the data from the user's contact over the public one
157 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
158 ($row['author-link'] == $row['contact-link'])) {
159 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
160 $row['author-avatar'] = $row['contact-avatar'];
162 if (isset($row['author-name']) && !empty($row['contact-name'])) {
163 $row['author-name'] = $row['contact-name'];
167 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
168 ($row['owner-link'] == $row['contact-link'])) {
169 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
170 $row['owner-avatar'] = $row['contact-avatar'];
172 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
173 $row['owner-name'] = $row['contact-name'];
177 // We can always comment on posts from these networks
178 if (array_key_exists('writable', $row) &&
179 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
180 $row['writable'] = true;
183 // ---------------------- Transform item content data ----------------------
185 // Fetch data from the item-content table whenever there is content there
186 if (self::isLegacyMode()) {
187 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
188 foreach ($legacy_fields as $field) {
189 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
190 $row[$field] = $row['internal-item-' . $field];
192 unset($row['internal-item-' . $field]);
196 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
197 $row['verb'] = self::indexToActivity($row['internal-activity']);
198 if (array_key_exists('title', $row)) {
201 if (array_key_exists('body', $row)) {
202 $row['body'] = $row['verb'];
204 if (array_key_exists('object', $row)) {
207 if (array_key_exists('object-type', $row)) {
208 $row['object-type'] = ACTIVITY_OBJ_NOTE;
210 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
211 // Posts don't have an object or target - but having tags or files.
212 // We safe some performance by building tag and file strings only here.
213 // We remove object and target since they aren't used for this type.
214 if (array_key_exists('object', $row)) {
217 if (array_key_exists('target', $row)) {
222 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
223 // Build the tag string out of the term entries
224 if (array_key_exists('tag', $row) && empty($row['tag'])) {
225 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
228 // Build the file string out of the term entries
229 if (array_key_exists('file', $row) && empty($row['file'])) {
230 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
234 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
235 $row['signed_text'] = $row['interaction'];
238 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
239 $row['ignored'] = $row['internal-user-ignored'];
242 // Remove internal fields
243 unset($row['internal-activity']);
244 unset($row['internal-network']);
245 unset($row['internal-iid']);
246 unset($row['internal-iaid']);
247 unset($row['internal-icid']);
248 unset($row['internal-user-ignored']);
249 unset($row['interaction']);
255 * @brief Fills an array with data from an item query
257 * @param object $stmt statement object
258 * @return array Data array
260 public static function inArray($stmt, $do_close = true) {
261 if (is_bool($stmt)) {
266 while ($row = self::fetch($stmt)) {
276 * @brief Check if item data exists
278 * @param array $condition array of fields for condition
280 * @return boolean Are there rows for that condition?
282 public static function exists($condition) {
283 $stmt = self::select(['id'], $condition, ['limit' => 1]);
285 if (is_bool($stmt)) {
288 $retval = (DBA::numRows($stmt) > 0);
297 * Retrieve a single record from the item table for a given user and returns it in an associative array
299 * @brief Retrieve a single record from a table
300 * @param integer $uid User ID
301 * @param array $fields
302 * @param array $condition
303 * @param array $params
307 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
309 $params['uid'] = $uid;
311 if (empty($selected)) {
312 $selected = Item::DISPLAY_FIELDLIST;
315 return self::selectFirst($selected, $condition, $params);
319 * @brief Select rows from the item table for a given user
321 * @param integer $uid User ID
322 * @param array $selected Array of selected fields, empty for all
323 * @param array $condition Array of fields for condition
324 * @param array $params Array of several parameters
326 * @return boolean|object
328 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
330 $params['uid'] = $uid;
332 if (empty($selected)) {
333 $selected = Item::DISPLAY_FIELDLIST;
336 return self::select($selected, $condition, $params);
340 * Retrieve a single record from the item table and returns it in an associative array
342 * @brief Retrieve a single record from a table
343 * @param array $fields
344 * @param array $condition
345 * @param array $params
349 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
351 $params['limit'] = 1;
353 $result = self::select($fields, $condition, $params);
355 if (is_bool($result)) {
358 $row = self::fetch($result);
365 * @brief Select rows from the item table
367 * @param array $selected Array of selected fields, empty for all
368 * @param array $condition Array of fields for condition
369 * @param array $params Array of several parameters
371 * @return boolean|object
373 public static function select(array $selected = [], array $condition = [], $params = [])
378 if (isset($params['uid'])) {
379 $uid = $params['uid'];
383 $fields = self::fieldlist($usermode);
385 $select_fields = self::constructSelectFields($fields, $selected);
387 $condition_string = DBA::buildCondition($condition);
389 $condition_string = self::addTablesToFields($condition_string, $fields);
392 $condition_string = $condition_string . ' AND ' . self::condition(false);
395 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
397 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
399 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
401 return DBA::p($sql, $condition);
405 * @brief Select rows from the starting post in the item table
407 * @param integer $uid User ID
408 * @param array $fields Array of selected fields, empty for all
409 * @param array $condition Array of fields for condition
410 * @param array $params Array of several parameters
412 * @return boolean|object
414 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
416 $params['uid'] = $uid;
418 if (empty($selected)) {
419 $selected = Item::DISPLAY_FIELDLIST;
422 return self::selectThread($selected, $condition, $params);
426 * Retrieve a single record from the starting post in the item table and returns it in an associative array
428 * @brief Retrieve a single record from a table
429 * @param integer $uid User ID
430 * @param array $selected
431 * @param array $condition
432 * @param array $params
436 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
438 $params['uid'] = $uid;
440 if (empty($selected)) {
441 $selected = Item::DISPLAY_FIELDLIST;
444 return self::selectFirstThread($selected, $condition, $params);
448 * Retrieve a single record from the starting post in the item table and returns it in an associative array
450 * @brief Retrieve a single record from a table
451 * @param array $fields
452 * @param array $condition
453 * @param array $params
457 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
459 $params['limit'] = 1;
460 $result = self::selectThread($fields, $condition, $params);
462 if (is_bool($result)) {
465 $row = self::fetch($result);
472 * @brief Select rows from the starting post in the item table
474 * @param array $selected Array of selected fields, empty for all
475 * @param array $condition Array of fields for condition
476 * @param array $params Array of several parameters
478 * @return boolean|object
480 public static function selectThread(array $selected = [], array $condition = [], $params = [])
485 if (isset($params['uid'])) {
486 $uid = $params['uid'];
490 $fields = self::fieldlist($usermode);
492 $fields['thread'] = ['mention', 'ignored', 'iid'];
494 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
495 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
496 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
497 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
499 $select_fields = self::constructSelectFields($fields, $selected);
501 $condition_string = DBA::buildCondition($condition);
503 $condition_string = self::addTablesToFields($condition_string, $threadfields);
504 $condition_string = self::addTablesToFields($condition_string, $fields);
507 $condition_string = $condition_string . ' AND ' . self::condition(true);
510 $param_string = DBA::buildParameter($params);
511 $param_string = self::addTablesToFields($param_string, $threadfields);
512 $param_string = self::addTablesToFields($param_string, $fields);
514 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
516 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
518 return DBA::p($sql, $condition);
522 * @brief Returns a list of fields that are associated with the item table
524 * @return array field list
526 private static function fieldlist($usermode)
530 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
531 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
532 'created', 'edited', 'commented', 'received', 'changed', 'psid',
533 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
534 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
535 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
536 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
537 'network' => 'internal-network', 'icid' => 'internal-icid',
538 'iaid' => 'internal-iaid'];
541 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
544 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
546 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
548 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
550 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
552 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
553 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
555 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
556 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
558 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
559 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
560 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
562 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
564 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
566 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
567 'start' => 'event-start','finish' => 'event-finish',
568 'summary' => 'event-summary','desc' => 'event-desc',
569 'location' => 'event-location', 'type' => 'event-type',
570 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
571 'ignore' => 'event-ignore', 'id' => 'event-id'];
573 $fields['sign'] = ['signed_text', 'signature', 'signer'];
575 $fields['diaspora-interaction'] = ['interaction'];
581 * @brief Returns SQL condition for the "select" functions
583 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
585 * @return string SQL condition
587 private static function condition($thread_mode)
590 $master_table = "`thread`";
592 $master_table = "`item`";
594 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
595 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
596 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
597 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
598 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
599 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
600 GRAVITY_PARENT, GRAVITY_PARENT);
604 * @brief Returns all needed "JOIN" commands for the "select" functions
606 * @param integer $uid User ID
607 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
608 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
610 * @return string The SQL joins for the "select" functions
612 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
615 $master_table = "`thread`";
616 $master_table_key = "`thread`.`iid`";
617 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
619 $master_table = "`item`";
620 $master_table_key = "`item`.`id`";
625 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
626 AND NOT `contact`.`blocked`
627 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
628 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
629 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
630 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
631 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
632 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
633 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
634 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
636 if (strpos($sql_commands, "`contact`.") !== false) {
637 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
639 if (strpos($sql_commands, "`author`.") !== false) {
640 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
642 if (strpos($sql_commands, "`owner`.") !== false) {
643 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
647 if (strpos($sql_commands, "`group_member`.") !== false) {
648 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
651 if (strpos($sql_commands, "`user`.") !== false) {
652 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
655 if (strpos($sql_commands, "`event`.") !== false) {
656 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
659 if (strpos($sql_commands, "`sign`.") !== false) {
660 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
663 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
664 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
667 if (strpos($sql_commands, "`item-activity`.") !== false) {
668 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
671 if (strpos($sql_commands, "`item-content`.") !== false) {
672 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
675 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
676 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
679 if (strpos($sql_commands, "`permissionset`.") !== false) {
680 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
683 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
684 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
687 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
688 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
695 * @brief Add the field list for the "select" functions
697 * @param array $fields The field definition array
698 * @param array $selected The array with the selected fields from the "select" functions
700 * @return string The field list
702 private static function constructSelectFields($fields, $selected)
704 if (!empty($selected)) {
705 $selected[] = 'internal-iid';
706 $selected[] = 'internal-iaid';
707 $selected[] = 'internal-icid';
708 $selected[] = 'internal-network';
711 if (in_array('verb', $selected)) {
712 $selected[] = 'internal-activity';
715 if (in_array('ignored', $selected)) {
716 $selected[] = 'internal-user-ignored';
719 if (in_array('signed_text', $selected)) {
720 $selected[] = 'interaction';
724 foreach ($fields as $table => $table_fields) {
725 foreach ($table_fields as $field => $select) {
726 if (empty($selected) || in_array($select, $selected)) {
727 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
728 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
729 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
731 if (is_int($field)) {
732 $selection[] = "`" . $table . "`.`" . $select . "`";
734 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
739 return implode(", ", $selection);
743 * @brief add table definition to fields in an SQL query
745 * @param string $query SQL query
746 * @param array $fields The field definition array
748 * @return string the changed SQL query
750 private static function addTablesToFields($query, $fields)
752 foreach ($fields as $table => $table_fields) {
753 foreach ($table_fields as $alias => $field) {
754 if (is_int($alias)) {
755 $replace_field = $field;
757 $replace_field = $alias;
760 $search = "/([^\.])`" . $field . "`/i";
761 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
762 $query = preg_replace($search, $replace, $query);
769 * @brief Update existing item entries
771 * @param array $fields The fields that are to be changed
772 * @param array $condition The condition for finding the item entries
774 * In the future we may have to change permissions as well.
775 * Then we had to add the user id as third parameter.
777 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
779 * @return integer|boolean number of affected rows - or "false" if there was an error
781 public static function update(array $fields, array $condition)
783 if (empty($condition) || empty($fields)) {
787 // To ensure the data integrity we do it in an transaction
790 // We cannot simply expand the condition to check for origin entries
791 // The condition needn't to be a simple array but could be a complex condition.
792 // And we have to execute this query before the update to ensure to fetch the same data.
793 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
795 $content_fields = [];
796 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
797 if (isset($fields[$field])) {
798 $content_fields[$field] = $fields[$field];
799 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
800 unset($fields[$field]);
802 $fields[$field] = null;
807 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
808 foreach ($clear_fields as $field) {
809 if (array_key_exists($field, $fields)) {
810 $fields[$field] = null;
814 if (array_key_exists('tag', $fields)) {
815 $tags = $fields['tag'];
816 $fields['tag'] = null;
821 if (array_key_exists('file', $fields)) {
822 $files = $fields['file'];
823 $fields['file'] = null;
828 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
829 'inform' => defaults($fields, 'inform', '')];
831 $fields['postopts'] = null;
832 $fields['inform'] = null;
834 if (!empty($fields)) {
835 $success = DBA::update('item', $fields, $condition);
844 // When there is no content for the "old" item table, this will count the fetched items
845 $rows = DBA::affectedRows();
847 while ($item = DBA::fetch($items)) {
848 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
849 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
851 if (empty($item['iaid'])) {
852 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
853 if (DBA::isResult($item_activity)) {
854 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
855 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
856 if (self::isLegacyMode()) {
857 $item_fields[$field] = null;
859 unset($item_fields[$field]);
862 DBA::update('item', $item_fields, ['id' => $item['id']]);
864 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
865 DBA::delete('item-content', ['id' => $item['icid']]);
868 } elseif (!empty($item['icid'])) {
869 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
871 if (!DBA::exists('item', ['icid' => $item['icid']])) {
872 DBA::delete('item-content', ['id' => $item['icid']]);
876 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
878 if (empty($item['icid'])) {
879 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
880 if (DBA::isResult($item_content)) {
881 $item_fields = ['icid' => $item_content['id']];
882 // Clear all fields in the item table that have a content in the item-content table
883 foreach ($item_content as $field => $content) {
884 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
885 if (self::isLegacyMode()) {
886 $item_fields[$field] = null;
888 unset($item_fields[$field]);
892 DBA::update('item', $item_fields, ['id' => $item['id']]);
898 Term::insertFromTagFieldByItemId($item['id'], $tags);
899 if (!empty($item['tag'])) {
900 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
904 if (!empty($files)) {
905 Term::insertFromFileFieldByItemId($item['id'], $files);
906 if (!empty($item['file'])) {
907 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
911 self::updateDeliveryData($item['id'], $delivery_data);
913 self::updateThread($item['id']);
915 // We only need to notfiy others when it is an original entry from us.
916 // Only call the notifier when the item has some content relevant change.
917 if ($item['origin'] && in_array('edited', array_keys($fields))) {
918 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
928 * @brief Delete an item and notify others about it - if it was ours
930 * @param array $condition The condition for finding the item entries
931 * @param integer $priority Priority for the notification
933 public static function delete($condition, $priority = PRIORITY_HIGH)
935 $items = self::select(['id'], $condition);
936 while ($item = self::fetch($items)) {
937 self::deleteById($item['id'], $priority);
943 * @brief Delete an item for an user and notify others about it - if it was ours
945 * @param array $condition The condition for finding the item entries
946 * @param integer $uid User who wants to delete this item
948 public static function deleteForUser($condition, $uid)
954 $items = self::select(['id', 'uid'], $condition);
955 while ($item = self::fetch($items)) {
956 // "Deleting" global items just means hiding them
957 if ($item['uid'] == 0) {
958 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
959 } elseif ($item['uid'] == $uid) {
960 self::deleteById($item['id'], PRIORITY_HIGH);
962 logger('Wrong ownership. Not deleting item ' . $item['id']);
969 * @brief Delete an item and notify others about it - if it was ours
971 * @param integer $item_id Item ID that should be delete
972 * @param integer $priority Priority for the notification
974 * @return boolean success
976 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
978 // locate item to be deleted
979 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
980 'deleted', 'file', 'resource-id', 'event-id', 'attach',
981 'verb', 'object-type', 'object', 'target', 'contact-id',
982 'icid', 'iaid', 'psid'];
983 $item = self::selectFirst($fields, ['id' => $item_id]);
984 if (!DBA::isResult($item)) {
985 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
989 if ($item['deleted']) {
990 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
994 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
995 if (!DBA::isResult($parent)) {
996 $parent = ['origin' => false];
999 // clean up categories and tags so they don't end up as orphans
1002 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1004 foreach ($matches as $mtch) {
1005 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1011 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1013 foreach ($matches as $mtch) {
1014 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1019 * If item is a link to a photo resource, nuke all the associated photos
1020 * (visitors will not have photo resources)
1021 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1022 * generate a resource-id and therefore aren't intimately linked to the item.
1024 if (strlen($item['resource-id'])) {
1025 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1028 // If item is a link to an event, delete the event.
1029 if (intval($item['event-id'])) {
1030 Event::delete($item['event-id']);
1033 // If item has attachments, drop them
1034 foreach (explode(", ", $item['attach']) as $attach) {
1035 preg_match("|attach/(\d+)|", $attach, $matches);
1036 if (is_array($matches) && count($matches) > 1) {
1037 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1041 // Delete tags that had been attached to other items
1042 self::deleteTagsFromItem($item);
1044 // Set the item to "deleted"
1045 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1046 DBA::update('item', $item_fields, ['id' => $item['id']]);
1048 Term::insertFromTagFieldByItemId($item['id'], '');
1049 Term::insertFromFileFieldByItemId($item['id'], '');
1050 self::deleteThread($item['id'], $item['parent-uri']);
1052 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1053 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1056 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1058 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1060 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1061 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1063 // When the permission set will be used in photo and events as well,
1064 // this query here needs to be extended.
1065 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1066 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1069 // If it's the parent of a comment thread, kill all the kids
1070 if ($item['id'] == $item['parent']) {
1071 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1074 // Is it our comment and/or our thread?
1075 if ($item['origin'] || $parent['origin']) {
1077 // When we delete the original post we will delete all existing copies on the server as well
1078 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1080 // send the notification upstream/downstream
1081 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1082 } elseif ($item['uid'] != 0) {
1084 // When we delete just our local user copy of an item, we have to set a marker to hide it
1085 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1086 if (DBA::isResult($global_item)) {
1087 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1091 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1096 private static function deleteTagsFromItem($item)
1098 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1102 $xo = XML::parseString($item["object"], false);
1103 $xt = XML::parseString($item["target"], false);
1105 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1109 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1110 if (!DBA::isResult($i)) {
1114 // For tags, the owner cannot remove the tag on the author's copy of the post.
1115 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1116 $author_copy = $item["origin"];
1118 if (($owner_remove && $author_copy) || !$owner_remove) {
1122 $tags = explode(',', $i["tag"]);
1125 foreach ($tags as $tag) {
1126 if (trim($tag) !== trim($xo->body)) {
1127 $newtags[] = trim($tag);
1131 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1134 private static function guid($item, $notify)
1136 if (!empty($item['guid'])) {
1137 return notags(trim($item['guid']));
1141 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1142 // We add the hash of our own host because our host is the original creator of the post.
1143 $prefix_host = get_app()->getHostName();
1147 // We are only storing the post so we create a GUID from the original hostname.
1148 if (!empty($item['author-link'])) {
1149 $parsed = parse_url($item['author-link']);
1150 if (!empty($parsed['host'])) {
1151 $prefix_host = $parsed['host'];
1155 if (empty($prefix_host) && !empty($item['plink'])) {
1156 $parsed = parse_url($item['plink']);
1157 if (!empty($parsed['host'])) {
1158 $prefix_host = $parsed['host'];
1162 if (empty($prefix_host) && !empty($item['uri'])) {
1163 $parsed = parse_url($item['uri']);
1164 if (!empty($parsed['host'])) {
1165 $prefix_host = $parsed['host'];
1169 // Is it in the format data@host.tld? - Used for mail contacts
1170 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1171 $mailparts = explode('@', $item['author-link']);
1172 $prefix_host = array_pop($mailparts);
1176 if (!empty($item['plink'])) {
1177 $guid = self::guidFromUri($item['plink'], $prefix_host);
1178 } elseif (!empty($item['uri'])) {
1179 $guid = self::guidFromUri($item['uri'], $prefix_host);
1181 $guid = System::createUUID(hash('crc32', $prefix_host));
1187 private static function contactId($item)
1189 $contact_id = (int)$item["contact-id"];
1191 if (!empty($contact_id)) {
1194 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1196 * First we are looking for a suitable contact that matches with the author of the post
1197 * This is done only for comments
1199 if ($item['parent-uri'] != $item['uri']) {
1200 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1203 // If not present then maybe the owner was found
1204 if ($contact_id == 0) {
1205 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1208 // Still missing? Then use the "self" contact of the current user
1209 if ($contact_id == 0) {
1210 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1211 if (DBA::isResult($self)) {
1212 $contact_id = $self["id"];
1215 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1220 // This function will finally cover most of the preparation functionality in mod/item.php
1221 public static function prepare(&$item)
1223 $data = BBCode::getAttachmentData($item['body']);
1224 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1225 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1226 $posttype = Item::PT_PAGE;
1227 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1231 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1235 // If it is a posting where users should get notifications, then define it as wall posting
1238 $item['origin'] = 1;
1239 $item['network'] = Protocol::DFRN;
1240 $item['protocol'] = Conversation::PARCEL_DFRN;
1242 if (is_int($notify)) {
1243 $priority = $notify;
1245 $priority = PRIORITY_HIGH;
1248 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1251 $item['guid'] = self::guid($item, $notify);
1252 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1255 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1257 // Store conversation data
1258 $item = Conversation::insert($item);
1261 * If a Diaspora signature structure was passed in, pull it out of the
1262 * item array and set it aside for later storage.
1266 if (isset($item['dsprsig'])) {
1267 $encoded_signature = $item['dsprsig'];
1268 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1269 unset($item['dsprsig']);
1272 $diaspora_signed_text = '';
1273 if (isset($item['diaspora_signed_text'])) {
1274 $diaspora_signed_text = $item['diaspora_signed_text'];
1275 unset($item['diaspora_signed_text']);
1278 // Converting the plink
1279 /// @TODO Check if this is really still needed
1280 if ($item['network'] == Protocol::OSTATUS) {
1281 if (isset($item['plink'])) {
1282 $item['plink'] = OStatus::convertHref($item['plink']);
1283 } elseif (isset($item['uri'])) {
1284 $item['plink'] = OStatus::convertHref($item['uri']);
1288 if (!empty($item['thr-parent'])) {
1289 $item['parent-uri'] = $item['thr-parent'];
1292 if (isset($item['gravity'])) {
1293 $item['gravity'] = intval($item['gravity']);
1294 } elseif ($item['parent-uri'] === $item['uri']) {
1295 $item['gravity'] = GRAVITY_PARENT;
1296 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1297 $item['gravity'] = GRAVITY_COMMENT;
1299 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1300 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1303 $uid = intval($item['uid']);
1305 // check for create date and expire time
1306 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1308 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1309 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1310 $expire_interval = $user['expire'];
1313 if (($expire_interval > 0) && !empty($item['created'])) {
1314 $expire_date = time() - ($expire_interval * 86400);
1315 $created_date = strtotime($item['created']);
1316 if ($created_date < $expire_date) {
1317 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1323 * Do we already have this item?
1324 * We have to check several networks since Friendica posts could be repeated
1325 * via OStatus (maybe Diasporsa as well)
1327 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1328 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1329 trim($item['uri']), $item['uid'],
1330 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1331 $existing = self::selectFirst(['id', 'network'], $condition);
1332 if (DBA::isResult($existing)) {
1333 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1335 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1338 return $existing["id"];
1342 $item['wall'] = intval(defaults($item, 'wall', 0));
1343 $item['extid'] = trim(defaults($item, 'extid', ''));
1344 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1345 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1346 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1347 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1348 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1349 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1350 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1351 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1352 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1353 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1354 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1355 $item['title'] = trim(defaults($item, 'title', ''));
1356 $item['location'] = trim(defaults($item, 'location', ''));
1357 $item['coord'] = trim(defaults($item, 'coord', ''));
1358 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1359 $item['deleted'] = 0;
1360 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1361 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1362 $item['verb'] = trim(defaults($item, 'verb', ''));
1363 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1364 $item['object'] = trim(defaults($item, 'object', ''));
1365 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1366 $item['target'] = trim(defaults($item, 'target', ''));
1367 $item['plink'] = trim(defaults($item, 'plink', ''));
1368 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1369 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1370 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1371 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1372 $item['private'] = intval(defaults($item, 'private', 0));
1373 $item['body'] = trim(defaults($item, 'body', ''));
1374 $item['tag'] = trim(defaults($item, 'tag', ''));
1375 $item['attach'] = trim(defaults($item, 'attach', ''));
1376 $item['app'] = trim(defaults($item, 'app', ''));
1377 $item['origin'] = intval(defaults($item, 'origin', 0));
1378 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1379 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1380 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1381 $item['inform'] = trim(defaults($item, 'inform', ''));
1382 $item['file'] = trim(defaults($item, 'file', ''));
1384 // When there is no content then we don't post it
1385 if ($item['body'].$item['title'] == '') {
1386 logger('No body, no title.');
1390 self::addLanguageToItemArray($item);
1392 // Items cannot be stored before they happen ...
1393 if ($item['created'] > DateTimeFormat::utcNow()) {
1394 $item['created'] = DateTimeFormat::utcNow();
1397 // We haven't invented time travel by now.
1398 if ($item['edited'] > DateTimeFormat::utcNow()) {
1399 $item['edited'] = DateTimeFormat::utcNow();
1402 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1404 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1405 $item["contact-id"] = self::contactId($item);
1407 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1408 'photo' => $item['author-avatar'], 'network' => $item['network']];
1410 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1412 if (Contact::isBlocked($item["author-id"])) {
1413 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1417 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1418 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1420 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1422 if (Contact::isBlocked($item["owner-id"])) {
1423 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1427 if ($item['network'] == Protocol::PHANTOM) {
1428 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1430 $item['network'] = Protocol::DFRN;
1431 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1434 // Checking if there is already an item with the same guid
1435 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1436 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1437 if (self::exists($condition)) {
1438 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1442 // Check for hashtags in the body and repair or add hashtag links
1443 self::setHashtags($item);
1445 $item['thr-parent'] = $item['parent-uri'];
1453 if ($item['parent-uri'] === $item['uri']) {
1455 $parent_deleted = 0;
1456 $allow_cid = $item['allow_cid'];
1457 $allow_gid = $item['allow_gid'];
1458 $deny_cid = $item['deny_cid'];
1459 $deny_gid = $item['deny_gid'];
1460 $notify_type = 'wall-new';
1462 // find the parent and snarf the item id and ACLs
1463 // and anything else we need to inherit
1465 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1466 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1467 'wall', 'private', 'forum_mode', 'origin'];
1468 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1469 $params = ['order' => ['id' => false]];
1470 $parent = self::selectFirst($fields, $condition, $params);
1472 if (DBA::isResult($parent)) {
1473 // is the new message multi-level threaded?
1474 // even though we don't support it now, preserve the info
1475 // and re-attach to the conversation parent.
1477 if ($parent['uri'] != $parent['parent-uri']) {
1478 $item['parent-uri'] = $parent['parent-uri'];
1480 $condition = ['uri' => $item['parent-uri'],
1481 'parent-uri' => $item['parent-uri'],
1482 'uid' => $item['uid']];
1483 $params = ['order' => ['id' => false]];
1484 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1486 if (DBA::isResult($toplevel_parent)) {
1487 $parent = $toplevel_parent;
1491 $parent_id = $parent['id'];
1492 $parent_deleted = $parent['deleted'];
1493 $allow_cid = $parent['allow_cid'];
1494 $allow_gid = $parent['allow_gid'];
1495 $deny_cid = $parent['deny_cid'];
1496 $deny_gid = $parent['deny_gid'];
1497 $item['wall'] = $parent['wall'];
1498 $notify_type = 'comment-new';
1501 * If the parent is private, force privacy for the entire conversation
1502 * This differs from the above settings as it subtly allows comments from
1503 * email correspondents to be private even if the overall thread is not.
1505 if ($parent['private']) {
1506 $item['private'] = $parent['private'];
1510 * Edge case. We host a public forum that was originally posted to privately.
1511 * The original author commented, but as this is a comment, the permissions
1512 * weren't fixed up so it will still show the comment as private unless we fix it here.
1514 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1515 $item['private'] = 0;
1518 // If its a post from myself then tag the thread as "mention"
1519 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1520 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1521 if (DBA::isResult($user)) {
1522 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1523 $self_id = Contact::getIdForURL($self, 0, true);
1524 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1525 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1526 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1527 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1532 * Allow one to see reply tweets from status.net even when
1533 * we don't have or can't see the original post.
1535 if ($force_parent) {
1536 logger('$force_parent=true, reply converted to top-level post.');
1538 $item['parent-uri'] = $item['uri'];
1539 $item['gravity'] = GRAVITY_PARENT;
1541 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1545 $parent_deleted = 0;
1549 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1550 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1552 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1553 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1554 if (self::exists($condition)) {
1555 logger('duplicated item with the same uri found. '.print_r($item,true));
1559 // On Friendica and Diaspora the GUID is unique
1560 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1561 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1562 if (self::exists($condition)) {
1563 logger('duplicated item with the same guid found. '.print_r($item,true));
1567 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1568 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1569 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1570 if (self::exists($condition)) {
1571 logger('duplicated item with the same body found. '.print_r($item,true));
1576 // Is this item available in the global items (with uid=0)?
1577 if ($item["uid"] == 0) {
1578 $item["global"] = true;
1580 // Set the global flag on all items if this was a global item entry
1581 self::update(['global' => true], ['uri' => $item["uri"]]);
1583 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1587 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1590 $private = $item['private'];
1593 $item["allow_cid"] = $allow_cid;
1594 $item["allow_gid"] = $allow_gid;
1595 $item["deny_cid"] = $deny_cid;
1596 $item["deny_gid"] = $deny_gid;
1597 $item["private"] = $private;
1598 $item["deleted"] = $parent_deleted;
1600 // Fill the cache field
1601 put_item_in_cache($item);
1604 $item['edit'] = false;
1605 $item['parent'] = $parent_id;
1606 Addon::callHooks('post_local', $item);
1607 unset($item['edit']);
1608 unset($item['parent']);
1610 Addon::callHooks('post_remote', $item);
1613 // This array field is used to trigger some automatic reactions
1614 // It is mainly used in the "post_local" hook.
1615 unset($item['api_source']);
1617 if (x($item, 'cancel')) {
1618 logger('post cancelled by addon.');
1623 * Check for already added items.
1624 * There is a timing issue here that sometimes creates double postings.
1625 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1627 if ($item["uid"] == 0) {
1628 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1629 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1634 logger('' . print_r($item,true), LOGGER_DATA);
1636 if (array_key_exists('tag', $item)) {
1637 $tags = $item['tag'];
1638 unset($item['tag']);
1643 if (array_key_exists('file', $item)) {
1644 $files = $item['file'];
1645 unset($item['file']);
1650 // Creates or assigns the permission set
1651 $item['psid'] = PermissionSet::fetchIDForPost($item);
1653 // We are doing this outside of the transaction to avoid timing problems
1654 if (!self::insertActivity($item)) {
1655 self::insertContent($item);
1658 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1659 'inform' => defaults($item, 'inform', '')];
1661 unset($item['postopts']);
1662 unset($item['inform']);
1664 // These fields aren't stored anymore in the item table, they are fetched upon request
1665 unset($item['author-link']);
1666 unset($item['author-name']);
1667 unset($item['author-avatar']);
1669 unset($item['owner-link']);
1670 unset($item['owner-name']);
1671 unset($item['owner-avatar']);
1674 $ret = DBA::insert('item', $item);
1676 // When the item was successfully stored we fetch the ID of the item.
1677 if (DBA::isResult($ret)) {
1678 $current_post = DBA::lastInsertId();
1680 // This can happen - for example - if there are locking timeouts.
1683 // Store the data into a spool file so that we can try again later.
1685 // At first we restore the Diaspora signature that we removed above.
1686 if (isset($encoded_signature)) {
1687 $item['dsprsig'] = $encoded_signature;
1690 // Now we store the data in the spool directory
1691 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1692 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1694 $spoolpath = get_spoolpath();
1695 if ($spoolpath != "") {
1696 $spool = $spoolpath.'/'.$file;
1698 // Ensure to have the removed data from above again in the item array
1699 $item = array_merge($item, $delivery_data);
1701 file_put_contents($spool, json_encode($item));
1702 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1707 if ($current_post == 0) {
1708 // This is one of these error messages that never should occur.
1709 logger("couldn't find created item - we better quit now.");
1714 // How much entries have we created?
1715 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1716 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1719 // There are duplicates. We delete our just created entry.
1720 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1722 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1723 DBA::delete('item', ['id' => $current_post]);
1726 } elseif ($entries == 0) {
1727 // This really should never happen since we quit earlier if there were problems.
1728 logger("Something is terribly wrong. We haven't found our created entry.");
1733 logger('created item '.$current_post);
1734 self::updateContact($item);
1736 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1737 $parent_id = $current_post;
1741 self::update(['parent' => $parent_id], ['id' => $current_post]);
1743 $item['id'] = $current_post;
1744 $item['parent'] = $parent_id;
1746 // update the commented timestamp on the parent
1747 // Only update "commented" if it is really a comment
1748 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1749 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1751 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1756 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1757 * We can check for this condition when we decode and encode the stuff again.
1759 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1760 $dsprsig->signature = base64_decode($dsprsig->signature);
1761 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1764 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1765 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1767 // The other fields are used by very old Friendica servers, so we currently store them differently
1768 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1769 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1773 if (!empty($diaspora_signed_text)) {
1774 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1777 $deleted = self::tagDeliver($item['uid'], $current_post);
1780 * current post can be deleted if is for a community page and no mention are
1783 if (!$deleted && !$dontcache) {
1784 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1785 if (DBA::isResult($posted_item)) {
1787 Addon::callHooks('post_local_end', $posted_item);
1789 Addon::callHooks('post_remote_end', $posted_item);
1792 logger('new item not found in DB, id ' . $current_post);
1796 if ($item['parent-uri'] === $item['uri']) {
1797 self::addThread($current_post);
1799 self::updateThread($parent_id);
1802 $delivery_data['iid'] = $current_post;
1804 self::insertDeliveryData($delivery_data);
1809 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1810 * This is not perfect - but a workable solution until we found the reason for the problem.
1812 if (!empty($tags)) {
1813 Term::insertFromTagFieldByItemId($current_post, $tags);
1816 if (!empty($files)) {
1817 Term::insertFromFileFieldByItemId($current_post, $files);
1820 if ($item['parent-uri'] === $item['uri']) {
1821 self::addShadow($current_post);
1823 self::addShadowPost($current_post);
1826 check_user_notification($current_post);
1829 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1830 } elseif (!empty($parent) && $parent['origin']) {
1831 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1834 return $current_post;
1838 * @brief Insert a new item delivery data entry
1840 * @param array $item The item fields that are to be inserted
1842 private static function insertDeliveryData($delivery_data)
1844 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1848 DBA::insert('item-delivery-data', $delivery_data);
1852 * @brief Update an existing item delivery data entry
1854 * @param integer $id The item id that is to be updated
1855 * @param array $item The item fields that are to be inserted
1857 private static function updateDeliveryData($id, $delivery_data)
1859 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1863 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1867 * @brief Insert a new item content entry
1869 * @param array $item The item fields that are to be inserted
1871 private static function insertActivity(&$item)
1873 $activity_index = self::activityToIndex($item['verb']);
1875 if ($activity_index < 0) {
1879 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1881 // We just remove everything that is content
1882 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1883 unset($item[$field]);
1886 // To avoid timing problems, we are using locks.
1887 $locked = Lock::acquire('item_insert_activity');
1889 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1892 // Do we already have this content?
1893 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1894 if (DBA::isResult($item_activity)) {
1895 $item['iaid'] = $item_activity['id'];
1896 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1897 } elseif (DBA::insert('item-activity', $fields)) {
1898 $item['iaid'] = DBA::lastInsertId();
1899 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1901 // This shouldn't happen.
1902 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1903 Lock::release('item_insert_activity');
1907 Lock::release('item_insert_activity');
1913 * @brief Insert a new item content entry
1915 * @param array $item The item fields that are to be inserted
1917 private static function insertContent(&$item)
1919 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1921 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1922 if (isset($item[$field])) {
1923 $fields[$field] = $item[$field];
1924 unset($item[$field]);
1928 // To avoid timing problems, we are using locks.
1929 $locked = Lock::acquire('item_insert_content');
1931 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1934 // Do we already have this content?
1935 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1936 if (DBA::isResult($item_content)) {
1937 $item['icid'] = $item_content['id'];
1938 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1939 } elseif (DBA::insert('item-content', $fields)) {
1940 $item['icid'] = DBA::lastInsertId();
1941 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1943 // This shouldn't happen.
1944 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1947 Lock::release('item_insert_content');
1952 * @brief Update existing item content entries
1954 * @param array $item The item fields that are to be changed
1955 * @param array $condition The condition for finding the item content entries
1957 private static function updateActivity($item, $condition)
1959 if (empty($item['verb'])) {
1962 $activity_index = self::activityToIndex($item['verb']);
1964 if ($activity_index < 0) {
1968 $fields = ['activity' => $activity_index];
1970 logger('Update activity for ' . json_encode($condition));
1972 DBA::update('item-activity', $fields, $condition, true);
1978 * @brief Update existing item content entries
1980 * @param array $item The item fields that are to be changed
1981 * @param array $condition The condition for finding the item content entries
1983 private static function updateContent($item, $condition)
1985 // We have to select only the fields from the "item-content" table
1987 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1988 if (isset($item[$field])) {
1989 $fields[$field] = $item[$field];
1993 if (empty($fields)) {
1994 // when there are no fields at all, just use the condition
1995 // This is to ensure that we always store content.
1996 $fields = $condition;
1999 logger('Update content for ' . json_encode($condition));
2001 DBA::update('item-content', $fields, $condition, true);
2005 * @brief Distributes public items to the receivers
2007 * @param integer $itemid Item ID that should be added
2008 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2010 public static function distribute($itemid, $signed_text = '')
2012 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2013 $parent = self::selectFirst(['owner-id'], $condition);
2014 if (!DBA::isResult($parent)) {
2018 // Only distribute public items from native networks
2019 $condition = ['id' => $itemid, 'uid' => 0,
2020 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2021 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2022 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2023 if (!DBA::isResult($item)) {
2027 $origin = $item['origin'];
2030 unset($item['parent']);
2031 unset($item['mention']);
2032 unset($item['wall']);
2033 unset($item['origin']);
2034 unset($item['starred']);
2038 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2039 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2040 if (!DBA::isResult($owner)) {
2044 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2045 $contacts = DBA::select('contact', ['uid'], $condition);
2046 while ($contact = DBA::fetch($contacts)) {
2047 if ($contact['uid'] == 0) {
2051 $users[$contact['uid']] = $contact['uid'];
2053 DBA::close($contacts);
2055 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2056 $contacts = DBA::select('contact', ['uid'], $condition);
2057 while ($contact = DBA::fetch($contacts)) {
2058 if ($contact['uid'] == 0) {
2062 $users[$contact['uid']] = $contact['uid'];
2064 DBA::close($contacts);
2066 if (!empty($owner['alias'])) {
2067 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2068 $contacts = DBA::select('contact', ['uid'], $condition);
2069 while ($contact = DBA::fetch($contacts)) {
2070 if ($contact['uid'] == 0) {
2074 $users[$contact['uid']] = $contact['uid'];
2076 DBA::close($contacts);
2081 if ($item['uri'] != $item['parent-uri']) {
2082 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2083 while ($parent = self::fetch($parents)) {
2084 $users[$parent['uid']] = $parent['uid'];
2085 if ($parent['origin'] && !$origin) {
2086 $origin_uid = $parent['uid'];
2091 foreach ($users as $uid) {
2092 if ($origin_uid == $uid) {
2093 $item['diaspora_signed_text'] = $signed_text;
2095 self::storeForUser($itemid, $item, $uid);
2100 * @brief Store public items for the receivers
2102 * @param integer $itemid Item ID that should be added
2103 * @param array $item The item entry that will be stored
2104 * @param integer $uid The user that will receive the item entry
2106 private static function storeForUser($itemid, $item, $uid)
2108 $item['uid'] = $uid;
2109 $item['origin'] = 0;
2111 if ($item['uri'] == $item['parent-uri']) {
2112 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2114 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2117 if (empty($item['contact-id'])) {
2118 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2119 if (!DBA::isResult($self)) {
2122 $item['contact-id'] = $self['id'];
2125 /// @todo Handling of "event-id"
2128 if ($item['uri'] == $item['parent-uri']) {
2129 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2130 if (DBA::isResult($contact)) {
2131 $notify = self::isRemoteSelf($contact, $item);
2135 $distributed = self::insert($item, false, $notify, true);
2137 if (!$distributed) {
2138 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2140 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2145 * @brief Add a shadow entry for a given item id that is a thread starter
2147 * We store every public item entry additionally with the user id "0".
2148 * This is used for the community page and for the search.
2149 * It is planned that in the future we will store public item entries only once.
2151 * @param integer $itemid Item ID that should be added
2153 public static function addShadow($itemid)
2155 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2156 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2157 $item = self::selectFirst($fields, $condition);
2159 if (!DBA::isResult($item)) {
2163 // is it already a copy?
2164 if (($itemid == 0) || ($item['uid'] == 0)) {
2168 // Is it a visible public post?
2169 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2173 // is it an entry from a connector? Only add an entry for natively connected networks
2174 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2178 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2182 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2184 if (DBA::isResult($item)) {
2185 // Preparing public shadow (removing user specific data)
2188 unset($item['parent']);
2189 unset($item['wall']);
2190 unset($item['mention']);
2191 unset($item['origin']);
2192 unset($item['starred']);
2193 unset($item['postopts']);
2194 unset($item['inform']);
2195 if ($item['uri'] == $item['parent-uri']) {
2196 $item['contact-id'] = $item['owner-id'];
2198 $item['contact-id'] = $item['author-id'];
2201 $public_shadow = self::insert($item, false, false, true);
2203 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2208 * @brief Add a shadow entry for a given item id that is a comment
2210 * This function does the same like the function above - but for comments
2212 * @param integer $itemid Item ID that should be added
2214 public static function addShadowPost($itemid)
2216 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2217 if (!DBA::isResult($item)) {
2221 // Is it a toplevel post?
2222 if ($item['id'] == $item['parent']) {
2223 self::addShadow($itemid);
2227 // Is this a shadow entry?
2228 if ($item['uid'] == 0) {
2232 // Is there a shadow parent?
2233 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2237 // Is there already a shadow entry?
2238 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2242 // Save "origin" and "parent" state
2243 $origin = $item['origin'];
2244 $parent = $item['parent'];
2246 // Preparing public shadow (removing user specific data)
2249 unset($item['parent']);
2250 unset($item['wall']);
2251 unset($item['mention']);
2252 unset($item['origin']);
2253 unset($item['starred']);
2254 unset($item['postopts']);
2255 unset($item['inform']);
2256 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2258 $public_shadow = self::insert($item, false, false, true);
2260 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2262 // If this was a comment to a Diaspora post we don't get our comment back.
2263 // This means that we have to distribute the comment by ourselves.
2264 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2265 self::distribute($public_shadow);
2270 * Adds a language specification in a "language" element of given $arr.
2271 * Expects "body" element to exist in $arr.
2273 private static function addLanguageToItemArray(&$item)
2275 $naked_body = BBCode::toPlaintext($item['body'], false);
2277 $ld = new Text_LanguageDetect();
2278 $ld->setNameMode(2);
2279 $languages = $ld->detect($naked_body, 3);
2281 if (is_array($languages)) {
2282 $item['language'] = json_encode($languages);
2287 * @brief Creates an unique guid out of a given uri
2289 * @param string $uri uri of an item entry
2290 * @param string $host hostname for the GUID prefix
2291 * @return string unique guid
2293 public static function guidFromUri($uri, $host)
2295 // Our regular guid routine is using this kind of prefix as well
2296 // We have to avoid that different routines could accidentally create the same value
2297 $parsed = parse_url($uri);
2299 // We use a hash of the hostname as prefix for the guid
2300 $guid_prefix = hash("crc32", $host);
2302 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2303 unset($parsed["scheme"]);
2305 // Glue it together to be able to make a hash from it
2306 $host_id = implode("/", $parsed);
2308 // We could use any hash algorithm since it isn't a security issue
2309 $host_hash = hash("ripemd128", $host_id);
2311 return $guid_prefix.$host_hash;
2315 * generate an unique URI
2317 * @param integer $uid User id
2318 * @param string $guid An existing GUID (Otherwise it will be generated)
2322 public static function newURI($uid, $guid = "")
2325 $guid = System::createUUID();
2328 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2332 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2334 * This can be used to filter for inactive contacts.
2335 * Only do this for public postings to avoid privacy problems, since poco data is public.
2336 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2338 * @param array $arr Contains the just posted item record
2340 private static function updateContact($arr)
2342 // Unarchive the author
2343 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2344 if (DBA::isResult($contact)) {
2345 Contact::unmarkForArchival($contact);
2348 // Unarchive the contact if it's not our own contact
2349 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2350 if (DBA::isResult($contact)) {
2351 Contact::unmarkForArchival($contact);
2354 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2356 // Is it a forum? Then we don't care about the rules from above
2357 if (!$update && ($arr["network"] == Protocol::DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2358 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2364 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2365 ['id' => $arr['contact-id']]);
2367 // Now do the same for the system wide contacts with uid=0
2368 if (!$arr['private']) {
2369 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2370 ['id' => $arr['owner-id']]);
2372 if ($arr['owner-id'] != $arr['author-id']) {
2373 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2374 ['id' => $arr['author-id']]);
2379 public static function setHashtags(&$item)
2382 $tags = get_tags($item["body"]);
2385 if (!count($tags)) {
2389 // This sorting is important when there are hashtags that are part of other hashtags
2390 // Otherwise there could be problems with hashtags like #test and #test2
2393 $URLSearchString = "^\[\]";
2395 // All hashtags should point to the home server if "local_tags" is activated
2396 if (Config::get('system', 'local_tags')) {
2397 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2398 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2400 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2401 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2404 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2405 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2407 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2410 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2412 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2415 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2417 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2420 // Repair recursive urls
2421 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2422 "#$2", $item["body"]);
2424 foreach ($tags as $tag) {
2425 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2429 $basetag = str_replace('_',' ',substr($tag,1));
2431 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2433 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2435 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2436 if (strlen($item["tag"])) {
2437 $item["tag"] = ','.$item["tag"];
2439 $item["tag"] = $newtag.$item["tag"];
2443 // Convert back the masked hashtags
2444 $item["body"] = str_replace("#", "#", $item["body"]);
2447 public static function getGuidById($id)
2449 $item = self::selectFirst(['guid'], ['id' => $id]);
2450 if (DBA::isResult($item)) {
2451 return $item['guid'];
2458 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2459 * @param string $guid item guid
2460 * @param int $uid user id
2461 * @return array with id and nick of the item with the given guid
2463 public static function getIdAndNickByGuid($guid, $uid = 0)
2469 $uid == local_user();
2472 // Does the given user have this item?
2474 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2475 if (DBA::isResult($item)) {
2476 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2477 if (!DBA::isResult($user)) {
2481 $nick = $user['nickname'];
2485 // Or is it anywhere on the server?
2487 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2488 $item = self::selectFirst(['id', 'uid'], $condition);
2489 if (DBA::isResult($item)) {
2490 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2491 if (!DBA::isResult($user)) {
2495 $nick = $user['nickname'];
2498 return ["nick" => $nick, "id" => $id];
2502 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2504 * @param int $item_id
2505 * @return bool true if item was deleted, else false
2507 private static function tagDeliver($uid, $item_id)
2511 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2512 if (!DBA::isResult($user)) {
2516 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2517 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2519 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2520 if (!DBA::isResult($item)) {
2524 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2527 * Diaspora uses their own hardwired link URL in @-tags
2528 * instead of the one we supply with webfinger
2530 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2532 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2534 foreach ($matches as $mtch) {
2535 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2537 logger('mention found: ' . $mtch[2]);
2543 if (($community_page || $prvgroup) &&
2544 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2545 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2547 logger("no-mention top-level post to community or private group. delete.");
2548 DBA::delete('item', ['id' => $item_id]);
2554 $arr = ['item' => $item, 'user' => $user];
2556 Addon::callHooks('tagged', $arr);
2558 if (!$community_page && !$prvgroup) {
2563 * tgroup delivery - setup a second delivery chain
2564 * prevent delivery looping - only proceed
2565 * if the message originated elsewhere and is a top-level post
2567 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2571 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2572 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2573 if (!DBA::isResult($self)) {
2577 $owner_id = Contact::getIdForURL($self['url']);
2579 // also reset all the privacy bits to the forum default permissions
2581 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2583 $psid = PermissionSet::fetchIDForPost($user);
2585 $forum_mode = ($prvgroup ? 2 : 1);
2587 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2588 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2589 self::update($fields, ['id' => $item_id]);
2591 self::updateThread($item_id);
2593 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2596 public static function isRemoteSelf($contact, &$datarray)
2600 if (!$contact['remote_self']) {
2604 // Prevent the forwarding of posts that are forwarded
2605 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2606 logger('Already forwarded', LOGGER_DEBUG);
2610 // Prevent to forward already forwarded posts
2611 if ($datarray["app"] == $a->getHostName()) {
2612 logger('Already forwarded (second test)', LOGGER_DEBUG);
2616 // Only forward posts
2617 if ($datarray["verb"] != ACTIVITY_POST) {
2618 logger('No post', LOGGER_DEBUG);
2622 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2623 logger('Not public', LOGGER_DEBUG);
2627 $datarray2 = $datarray;
2628 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2629 if ($contact['remote_self'] == 2) {
2630 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2631 ['uid' => $contact['uid'], 'self' => true]);
2632 if (DBA::isResult($self)) {
2633 $datarray['contact-id'] = $self["id"];
2635 $datarray['owner-name'] = $self["name"];
2636 $datarray['owner-link'] = $self["url"];
2637 $datarray['owner-avatar'] = $self["thumb"];
2639 $datarray['author-name'] = $datarray['owner-name'];
2640 $datarray['author-link'] = $datarray['owner-link'];
2641 $datarray['author-avatar'] = $datarray['owner-avatar'];
2643 unset($datarray['created']);
2644 unset($datarray['edited']);
2646 unset($datarray['network']);
2647 unset($datarray['owner-id']);
2648 unset($datarray['author-id']);
2651 if ($contact['network'] != Protocol::FEED) {
2652 $datarray["guid"] = System::createUUID();
2653 unset($datarray["plink"]);
2654 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2655 $datarray["parent-uri"] = $datarray["uri"];
2656 $datarray["thr-parent"] = $datarray["uri"];
2657 $datarray["extid"] = Protocol::DFRN;
2658 $urlpart = parse_url($datarray2['author-link']);
2659 $datarray["app"] = $urlpart["host"];
2661 $datarray['private'] = 0;
2665 if ($contact['network'] != Protocol::FEED) {
2666 // Store the original post
2667 $result = self::insert($datarray2, false, false);
2668 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2670 $datarray["app"] = "Feed";
2674 // Trigger automatic reactions for addons
2675 $datarray['api_source'] = true;
2677 // We have to tell the hooks who we are - this really should be improved
2678 $_SESSION["authenticated"] = true;
2679 $_SESSION["uid"] = $contact['uid'];
2688 * @param array $item
2692 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2694 if (Config::get('system', 'disable_embedded')) {
2698 logger('check for photos', LOGGER_DEBUG);
2699 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2704 $img_start = strpos($orig_body, '[img');
2705 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2706 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2708 while (($img_st_close !== false) && ($img_len !== false)) {
2709 $img_st_close++; // make it point to AFTER the closing bracket
2710 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2712 logger('found photo ' . $image, LOGGER_DEBUG);
2714 if (stristr($image, $site . '/photo/')) {
2715 // Only embed locally hosted photos
2717 $i = basename($image);
2718 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2719 $x = strpos($i, '-');
2722 $res = substr($i, $x + 1);
2723 $i = substr($i, 0, $x);
2724 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2725 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2726 if (DBA::isResult($photo)) {
2728 * Check to see if we should replace this photo link with an embedded image
2729 * 1. No need to do so if the photo is public
2730 * 2. If there's a contact-id provided, see if they're in the access list
2731 * for the photo. If so, embed it.
2732 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2733 * permissions, regardless of order but first check to see if they're an exact
2734 * match to save some processing overhead.
2736 if (self::hasPermissions($photo)) {
2738 $recips = self::enumeratePermissions($photo);
2739 if (in_array($cid, $recips)) {
2743 if (self::samePermissions($item, $photo)) {
2749 $data = $photo['data'];
2750 $type = $photo['type'];
2752 // If a custom width and height were specified, apply before embedding
2753 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2754 logger('scaling photo', LOGGER_DEBUG);
2756 $width = intval($match[1]);
2757 $height = intval($match[2]);
2759 $Image = new Image($data, $type);
2760 if ($Image->isValid()) {
2761 $Image->scaleDown(max($width, $height));
2762 $data = $Image->asString();
2763 $type = $Image->getType();
2767 logger('replacing photo', LOGGER_DEBUG);
2768 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2769 logger('replaced: ' . $image, LOGGER_DATA);
2775 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2776 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2777 if ($orig_body === false) {
2781 $img_start = strpos($orig_body, '[img');
2782 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2783 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2786 $new_body = $new_body . $orig_body;
2791 private static function hasPermissions($obj)
2793 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2794 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2797 private static function samePermissions($obj1, $obj2)
2799 // first part is easy. Check that these are exactly the same.
2800 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2801 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2802 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2803 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2807 // This is harder. Parse all the permissions and compare the resulting set.
2808 $recipients1 = self::enumeratePermissions($obj1);
2809 $recipients2 = self::enumeratePermissions($obj2);
2813 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2814 return ($recipients1 == $recipients2);
2817 // returns an array of contact-ids that are allowed to see this object
2818 public static function enumeratePermissions($obj)
2820 $allow_people = expand_acl($obj['allow_cid']);
2821 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2822 $deny_people = expand_acl($obj['deny_cid']);
2823 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2824 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2825 $deny = array_unique(array_merge($deny_people, $deny_groups));
2826 $recipients = array_diff($recipients, $deny);
2830 public static function getFeedTags($item)
2834 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2836 for ($x = 0; $x < $cnt; $x ++) {
2837 if ($matches[1][$x]) {
2838 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2843 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2845 for ($x = 0; $x < $cnt; $x ++) {
2846 if ($matches[1][$x]) {
2847 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2854 public static function expire($uid, $days, $network = "", $force = false)
2856 if (!$uid || ($days < 1)) {
2860 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2861 $uid, GRAVITY_PARENT];
2864 * $expire_network_only = save your own wall posts
2865 * and just expire conversations started by others
2867 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2869 if ($expire_network_only) {
2870 $condition[0] .= " AND NOT `wall`";
2873 if ($network != "") {
2874 $condition[0] .= " AND `network` = ?";
2875 $condition[] = $network;
2878 * There is an index "uid_network_received" but not "uid_network_created"
2879 * This avoids the creation of another index just for one purpose.
2880 * And it doesn't really matter wether to look at "received" or "created"
2882 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2883 $condition[] = $days;
2885 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2886 $condition[] = $days;
2889 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2891 if (!DBA::isResult($items)) {
2895 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2897 // Forcing expiring of items - but not notes and marked items
2899 $expire_items = true;
2902 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2903 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2904 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2908 while ($item = Item::fetch($items)) {
2909 // don't expire filed items
2911 if (strpos($item['file'], '[') !== false) {
2915 // Only expire posts, not photos and photo comments
2917 if (!$expire_photos && strlen($item['resource-id'])) {
2919 } elseif (!$expire_starred && intval($item['starred'])) {
2921 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2923 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2927 self::deleteById($item['id'], PRIORITY_LOW);
2932 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2935 public static function firstPostDate($uid, $wall = false)
2937 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2938 $params = ['order' => ['created' => false]];
2939 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2940 if (DBA::isResult($thread)) {
2941 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2947 * @brief add/remove activity to an item
2949 * Toggle activities as like,dislike,attend of an item
2951 * @param string $item_id
2952 * @param string $verb
2953 * Activity verb. One of
2954 * like, unlike, dislike, undislike, attendyes, unattendyes,
2955 * attendno, unattendno, attendmaybe, unattendmaybe
2956 * @hook 'post_local_end'
2958 * 'post_id' => ID of posted item
2960 public static function performLike($item_id, $verb)
2962 if (!local_user() && !remote_user()) {
2969 $activity = ACTIVITY_LIKE;
2973 $activity = ACTIVITY_DISLIKE;
2977 $activity = ACTIVITY_ATTEND;
2981 $activity = ACTIVITY_ATTENDNO;
2984 case 'unattendmaybe':
2985 $activity = ACTIVITY_ATTENDMAYBE;
2988 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2992 // Enable activity toggling instead of on/off
2993 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2995 logger('like: verb ' . $verb . ' item ' . $item_id);
2997 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2998 if (!DBA::isResult($item)) {
2999 logger('like: unknown item ' . $item_id);
3003 $item_uri = $item['uri'];
3005 $uid = $item['uid'];
3006 if (($uid == 0) && local_user()) {
3007 $uid = local_user();
3010 if (!can_write_wall($uid)) {
3011 logger('like: unable to write on wall ' . $uid);
3015 // Retrieves the local post owner
3016 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3017 if (!DBA::isResult($owner_self_contact)) {
3018 logger('like: unknown owner ' . $uid);
3022 // Retrieve the current logged in user's public contact
3023 $author_id = public_contact();
3025 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3026 if (!DBA::isResult($author_contact)) {
3027 logger('like: unknown author ' . $author_id);
3031 // Contact-id is the uid-dependant author contact
3032 if (local_user() == $uid) {
3033 $item_contact_id = $owner_self_contact['id'];
3034 $item_contact = $owner_self_contact;
3036 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3037 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3038 if (!DBA::isResult($item_contact)) {
3039 logger('like: unknown item contact ' . $item_contact_id);
3044 // Look for an existing verb row
3045 // event participation are essentially radio toggles. If you make a subsequent choice,
3046 // we need to eradicate your first choice.
3047 if ($event_verb_flag) {
3048 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3050 // Translate to the index based activity index
3052 foreach ($verbs as $verb) {
3053 $activities[] = self::activityToIndex($verb);
3056 $activities = self::activityToIndex($activity);
3059 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3060 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3062 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3064 // If it exists, mark it as deleted
3065 if (DBA::isResult($like_item)) {
3066 self::deleteById($like_item['id']);
3068 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3073 // Verb is "un-something", just trying to delete existing entries
3074 if (strpos($verb, 'un') === 0) {
3078 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3081 'guid' => System::createUUID(),
3082 'uri' => self::newURI($item['uid']),
3083 'uid' => $item['uid'],
3084 'contact-id' => $item_contact_id,
3085 'wall' => $item['wall'],
3087 'network' => Protocol::DFRN,
3088 'gravity' => GRAVITY_ACTIVITY,
3089 'parent' => $item['id'],
3090 'parent-uri' => $item['uri'],
3091 'thr-parent' => $item['uri'],
3092 'owner-id' => $author_id,
3093 'author-id' => $author_id,
3094 'body' => $activity,
3095 'verb' => $activity,
3096 'object-type' => $objtype,
3097 'allow_cid' => $item['allow_cid'],
3098 'allow_gid' => $item['allow_gid'],
3099 'deny_cid' => $item['deny_cid'],
3100 'deny_gid' => $item['deny_gid'],
3105 $new_item_id = self::insert($new_item);
3107 // If the parent item isn't visible then set it to visible
3108 if (!$item['visible']) {
3109 self::update(['visible' => true], ['id' => $item['id']]);
3112 // Save the author information for the like in case we need to relay to Diaspora
3113 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3115 $new_item['id'] = $new_item_id;
3117 Addon::callHooks('post_local_end', $new_item);
3119 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3124 private static function addThread($itemid, $onlyshadow = false)
3126 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3127 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3128 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3129 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3130 $item = self::selectFirst($fields, $condition);
3132 if (!DBA::isResult($item)) {
3136 $item['iid'] = $itemid;
3139 $result = DBA::insert('thread', $item);
3141 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3145 private static function updateThread($itemid, $setmention = false)
3147 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3148 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3149 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3150 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3152 $item = self::selectFirst($fields, $condition);
3153 if (!DBA::isResult($item)) {
3158 $item["mention"] = 1;
3165 foreach ($item as $field => $data) {
3166 if (!in_array($field, ["guid"])) {
3167 $fields[$field] = $data;
3171 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3173 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3176 private static function deleteThread($itemid, $itemuri = "")
3178 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3179 if (!DBA::isResult($item)) {
3180 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3184 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3186 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3188 if ($itemuri != "") {
3189 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3190 if (!self::exists($condition)) {
3191 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3192 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);