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 Friendica\Util\Security;
28 use Text_LanguageDetect;
30 require_once 'boot.php';
31 require_once 'include/items.php';
32 require_once 'include/text.php';
34 class Item extends BaseObject
36 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
43 const PT_DOCUMENT = 19;
45 const PT_PERSONAL_NOTE = 128;
47 // Field list that is used to display the items
48 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
49 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
50 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
51 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
52 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
53 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
54 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
55 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
56 'writable', 'self', 'cid', 'alias',
57 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
58 'event-summary', 'event-desc', 'event-location', 'event-type',
59 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
61 // Field list that is used to deliver items via the protocols
62 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
63 'created', 'edited', 'verb', 'object-type', 'object', 'target',
64 'private', 'title', 'body', 'location', 'coord', 'app',
65 'attach', 'tag', 'deleted', 'extid', 'post-type',
66 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
67 'author-id', 'author-link', 'owner-link', 'contact-uid',
68 'signed_text', 'signature', 'signer', 'network'];
70 // Field list for "item-content" table that is mixed with the item table
71 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
72 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
73 'object-type', 'object', 'target-type', 'target', 'plink'];
75 // Field list for "item-content" table that is not present in the "item" table
76 const CONTENT_FIELDLIST = ['language'];
78 // Field list for additional delivery data
79 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
81 // All fields in the item table
82 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
83 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
84 'uri-hash', 'created', 'edited', 'commented', 'received', 'changed', 'verb',
85 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
86 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
87 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
88 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
89 'title', 'content-warning', 'body', 'location', 'coord', 'app',
90 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
91 'author-id', 'author-link', 'author-name', 'author-avatar',
92 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
94 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
95 // The item-activity table only stores the index and needs this array to know the matching activity.
96 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
98 private static $legacy_mode = null;
100 public static function isLegacyMode()
102 if (is_null(self::$legacy_mode)) {
103 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
106 return self::$legacy_mode;
110 * @brief returns an activity index from an activity string
112 * @param string $activity activity string
113 * @return integer Activity index
115 public static function activityToIndex($activity)
117 $index = array_search($activity, self::ACTIVITIES);
119 if (is_bool($index)) {
127 * @brief returns an activity string from an activity index
129 * @param integer $index activity index
130 * @return string Activity string
132 private static function indexToActivity($index)
134 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
138 return self::ACTIVITIES[$index];
142 * @brief Fetch a single item row
144 * @param mixed $stmt statement object
145 * @return array current row
147 public static function fetch($stmt)
149 $row = DBA::fetch($stmt);
155 // ---------------------- Transform item structure data ----------------------
157 // We prefer the data from the user's contact over the public one
158 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
159 ($row['author-link'] == $row['contact-link'])) {
160 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
161 $row['author-avatar'] = $row['contact-avatar'];
163 if (isset($row['author-name']) && !empty($row['contact-name'])) {
164 $row['author-name'] = $row['contact-name'];
168 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
169 ($row['owner-link'] == $row['contact-link'])) {
170 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
171 $row['owner-avatar'] = $row['contact-avatar'];
173 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
174 $row['owner-name'] = $row['contact-name'];
178 // We can always comment on posts from these networks
179 if (array_key_exists('writable', $row) &&
180 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
181 $row['writable'] = true;
184 // ---------------------- Transform item content data ----------------------
186 // Fetch data from the item-content table whenever there is content there
187 if (self::isLegacyMode()) {
188 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
189 foreach ($legacy_fields as $field) {
190 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
191 $row[$field] = $row['internal-item-' . $field];
193 unset($row['internal-item-' . $field]);
197 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
198 $row['verb'] = self::indexToActivity($row['internal-activity']);
199 if (array_key_exists('title', $row)) {
202 if (array_key_exists('body', $row)) {
203 $row['body'] = $row['verb'];
205 if (array_key_exists('object', $row)) {
208 if (array_key_exists('object-type', $row)) {
209 $row['object-type'] = ACTIVITY_OBJ_NOTE;
211 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
212 // Posts don't have an object or target - but having tags or files.
213 // We safe some performance by building tag and file strings only here.
214 // We remove object and target since they aren't used for this type.
215 if (array_key_exists('object', $row)) {
218 if (array_key_exists('target', $row)) {
223 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
224 // Build the tag string out of the term entries
225 if (array_key_exists('tag', $row) && empty($row['tag'])) {
226 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
229 // Build the file string out of the term entries
230 if (array_key_exists('file', $row) && empty($row['file'])) {
231 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
235 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
236 $row['signed_text'] = $row['interaction'];
239 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
240 $row['ignored'] = $row['internal-user-ignored'];
243 // Remove internal fields
244 unset($row['internal-activity']);
245 unset($row['internal-network']);
246 unset($row['internal-iid']);
247 unset($row['internal-iaid']);
248 unset($row['internal-icid']);
249 unset($row['internal-user-ignored']);
250 unset($row['interaction']);
256 * @brief Fills an array with data from an item query
258 * @param object $stmt statement object
259 * @return array Data array
261 public static function inArray($stmt, $do_close = true) {
262 if (is_bool($stmt)) {
267 while ($row = self::fetch($stmt)) {
277 * @brief Check if item data exists
279 * @param array $condition array of fields for condition
281 * @return boolean Are there rows for that condition?
283 public static function exists($condition) {
284 $stmt = self::select(['id'], $condition, ['limit' => 1]);
286 if (is_bool($stmt)) {
289 $retval = (DBA::numRows($stmt) > 0);
298 * Retrieve a single record from the item table for a given user and returns it in an associative array
300 * @brief Retrieve a single record from a table
301 * @param integer $uid User ID
302 * @param array $fields
303 * @param array $condition
304 * @param array $params
308 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
310 $params['uid'] = $uid;
312 if (empty($selected)) {
313 $selected = Item::DISPLAY_FIELDLIST;
316 return self::selectFirst($selected, $condition, $params);
320 * @brief Select rows from the item table for a given user
322 * @param integer $uid User ID
323 * @param array $selected Array of selected fields, empty for all
324 * @param array $condition Array of fields for condition
325 * @param array $params Array of several parameters
327 * @return boolean|object
329 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
331 $params['uid'] = $uid;
333 if (empty($selected)) {
334 $selected = Item::DISPLAY_FIELDLIST;
337 return self::select($selected, $condition, $params);
341 * Retrieve a single record from the item table and returns it in an associative array
343 * @brief Retrieve a single record from a table
344 * @param array $fields
345 * @param array $condition
346 * @param array $params
350 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
352 $params['limit'] = 1;
354 $result = self::select($fields, $condition, $params);
356 if (is_bool($result)) {
359 $row = self::fetch($result);
366 * @brief Select rows from the item table
368 * @param array $selected Array of selected fields, empty for all
369 * @param array $condition Array of fields for condition
370 * @param array $params Array of several parameters
372 * @return boolean|object
374 public static function select(array $selected = [], array $condition = [], $params = [])
379 if (isset($params['uid'])) {
380 $uid = $params['uid'];
384 $fields = self::fieldlist($selected, $usermode);
386 $select_fields = self::constructSelectFields($fields, $selected);
388 $condition_string = DBA::buildCondition($condition);
390 $condition_string = self::addTablesToFields($condition_string, $fields);
393 $condition_string = $condition_string . ' AND ' . self::condition(false);
396 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
398 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
400 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
402 return DBA::p($sql, $condition);
406 * @brief Select rows from the starting post in the item table
408 * @param integer $uid User ID
409 * @param array $fields Array of selected fields, empty for all
410 * @param array $condition Array of fields for condition
411 * @param array $params Array of several parameters
413 * @return boolean|object
415 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
417 $params['uid'] = $uid;
419 if (empty($selected)) {
420 $selected = Item::DISPLAY_FIELDLIST;
423 return self::selectThread($selected, $condition, $params);
427 * Retrieve a single record from the starting post in the item table and returns it in an associative array
429 * @brief Retrieve a single record from a table
430 * @param integer $uid User ID
431 * @param array $selected
432 * @param array $condition
433 * @param array $params
437 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
439 $params['uid'] = $uid;
441 if (empty($selected)) {
442 $selected = Item::DISPLAY_FIELDLIST;
445 return self::selectFirstThread($selected, $condition, $params);
449 * Retrieve a single record from the starting post in the item table and returns it in an associative array
451 * @brief Retrieve a single record from a table
452 * @param array $fields
453 * @param array $condition
454 * @param array $params
458 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
460 $params['limit'] = 1;
461 $result = self::selectThread($fields, $condition, $params);
463 if (is_bool($result)) {
466 $row = self::fetch($result);
473 * @brief Select rows from the starting post in the item table
475 * @param array $selected Array of selected fields, empty for all
476 * @param array $condition Array of fields for condition
477 * @param array $params Array of several parameters
479 * @return boolean|object
481 public static function selectThread(array $selected = [], array $condition = [], $params = [])
486 if (isset($params['uid'])) {
487 $uid = $params['uid'];
491 $fields = self::fieldlist($selected, $usermode);
493 $fields['thread'] = ['mention', 'ignored', 'iid'];
495 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
496 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
497 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
498 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
500 $select_fields = self::constructSelectFields($fields, $selected);
502 $condition_string = DBA::buildCondition($condition);
504 $condition_string = self::addTablesToFields($condition_string, $threadfields);
505 $condition_string = self::addTablesToFields($condition_string, $fields);
508 $condition_string = $condition_string . ' AND ' . self::condition(true);
511 $param_string = DBA::buildParameter($params);
512 $param_string = self::addTablesToFields($param_string, $threadfields);
513 $param_string = self::addTablesToFields($param_string, $fields);
515 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
517 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
519 return DBA::p($sql, $condition);
523 * @brief Returns a list of fields that are associated with the item table
525 * @return array field list
527 private static function fieldlist($selected, $usermode)
531 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
532 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
533 'created', 'edited', 'commented', 'received', 'changed', 'psid', 'uri-hash',
534 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
535 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
536 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
537 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
538 'network' => 'internal-network', 'icid' => 'internal-icid',
539 'iaid' => 'internal-iaid'];
542 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
545 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
547 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
549 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
551 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
553 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
554 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
556 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
557 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
559 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
560 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
561 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
563 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
565 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
567 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
568 'start' => 'event-start','finish' => 'event-finish',
569 'summary' => 'event-summary','desc' => 'event-desc',
570 'location' => 'event-location', 'type' => 'event-type',
571 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
572 'ignore' => 'event-ignore', 'id' => 'event-id'];
574 $fields['sign'] = ['signed_text', 'signature', 'signer'];
576 $fields['diaspora-interaction'] = ['interaction'];
582 * @brief Returns SQL condition for the "select" functions
584 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
586 * @return string SQL condition
588 private static function condition($thread_mode)
591 $master_table = "`thread`";
593 $master_table = "`item`";
595 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
596 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
597 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
598 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
599 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
600 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
601 GRAVITY_PARENT, GRAVITY_PARENT);
605 * @brief Returns all needed "JOIN" commands for the "select" functions
607 * @param integer $uid User ID
608 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
609 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
611 * @return string The SQL joins for the "select" functions
613 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
616 $master_table = "`thread`";
617 $master_table_key = "`thread`.`iid`";
618 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
620 $master_table = "`item`";
621 $master_table_key = "`item`.`id`";
626 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
627 AND NOT `contact`.`blocked`
628 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
629 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
630 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
631 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
632 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
633 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
634 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
635 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
637 if (strpos($sql_commands, "`contact`.") !== false) {
638 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
640 if (strpos($sql_commands, "`author`.") !== false) {
641 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
643 if (strpos($sql_commands, "`owner`.") !== false) {
644 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
648 if (strpos($sql_commands, "`group_member`.") !== false) {
649 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
652 if (strpos($sql_commands, "`user`.") !== false) {
653 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
656 if (strpos($sql_commands, "`event`.") !== false) {
657 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
660 if (strpos($sql_commands, "`sign`.") !== false) {
661 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
664 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
665 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
668 if (strpos($sql_commands, "`item-activity`.") !== false) {
669 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
672 if (strpos($sql_commands, "`item-content`.") !== false) {
673 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
676 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
677 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
680 if (strpos($sql_commands, "`permissionset`.") !== false) {
681 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
684 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
685 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
688 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
689 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
696 * @brief Add the field list for the "select" functions
698 * @param array $fields The field definition array
699 * @param array $selected The array with the selected fields from the "select" functions
701 * @return string The field list
703 private static function constructSelectFields($fields, $selected)
705 if (!empty($selected)) {
706 $selected[] = 'internal-iid';
707 $selected[] = 'internal-iaid';
708 $selected[] = 'internal-icid';
709 $selected[] = 'internal-network';
712 if (in_array('verb', $selected)) {
713 $selected[] = 'internal-activity';
716 if (in_array('ignored', $selected)) {
717 $selected[] = 'internal-user-ignored';
720 if (in_array('signed_text', $selected)) {
721 $selected[] = 'interaction';
725 foreach ($fields as $table => $table_fields) {
726 foreach ($table_fields as $field => $select) {
727 if (empty($selected) || in_array($select, $selected)) {
728 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
729 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
730 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
732 if (is_int($field)) {
733 $selection[] = "`" . $table . "`.`" . $select . "`";
735 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
740 return implode(", ", $selection);
744 * @brief add table definition to fields in an SQL query
746 * @param string $query SQL query
747 * @param array $fields The field definition array
749 * @return string the changed SQL query
751 private static function addTablesToFields($query, $fields)
753 foreach ($fields as $table => $table_fields) {
754 foreach ($table_fields as $alias => $field) {
755 if (is_int($alias)) {
756 $replace_field = $field;
758 $replace_field = $alias;
761 $search = "/([^\.])`" . $field . "`/i";
762 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
763 $query = preg_replace($search, $replace, $query);
770 * @brief Generate a server unique item hash for linking between the item tables
772 * @param string $uri Item URI
773 * @param date $created Item creation date
775 * @return string the item hash
777 private static function itemHash($uri, $created)
779 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
783 * @brief Update existing item entries
785 * @param array $fields The fields that are to be changed
786 * @param array $condition The condition for finding the item entries
788 * In the future we may have to change permissions as well.
789 * Then we had to add the user id as third parameter.
791 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
793 * @return integer|boolean number of affected rows - or "false" if there was an error
795 public static function update(array $fields, array $condition)
797 if (empty($condition) || empty($fields)) {
801 // To ensure the data integrity we do it in an transaction
804 // We cannot simply expand the condition to check for origin entries
805 // The condition needn't to be a simple array but could be a complex condition.
806 // And we have to execute this query before the update to ensure to fetch the same data.
807 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
809 $content_fields = [];
810 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
811 if (isset($fields[$field])) {
812 $content_fields[$field] = $fields[$field];
813 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
814 unset($fields[$field]);
816 $fields[$field] = null;
821 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
822 foreach ($clear_fields as $field) {
823 if (array_key_exists($field, $fields)) {
824 $fields[$field] = null;
828 if (array_key_exists('tag', $fields)) {
829 $tags = $fields['tag'];
830 $fields['tag'] = null;
835 if (array_key_exists('file', $fields)) {
836 $files = $fields['file'];
837 $fields['file'] = null;
842 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
843 'inform' => defaults($fields, 'inform', '')];
845 $fields['postopts'] = null;
846 $fields['inform'] = null;
848 if (!empty($fields)) {
849 $success = DBA::update('item', $fields, $condition);
858 // When there is no content for the "old" item table, this will count the fetched items
859 $rows = DBA::affectedRows();
861 while ($item = DBA::fetch($items)) {
863 // This part here can safely be removed when the legacy fields in the item had been removed
864 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
866 // Fetch the uri-hash from an existing item entry if there is one
867 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
868 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
869 if (DBA::isResult($existing)) {
870 $item['uri-hash'] = $existing['uri-hash'];
872 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
875 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
876 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
877 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
880 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
881 if (!empty($item['iaid'])) {
882 $update_condition = ['id' => $item['iaid']];
884 $update_condition = ['uri-hash' => $item['uri-hash']];
886 self::updateActivity($content_fields, $update_condition);
888 if (empty($item['iaid'])) {
889 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
890 if (DBA::isResult($item_activity)) {
891 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
892 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
893 if (self::isLegacyMode()) {
894 $item_fields[$field] = null;
896 unset($item_fields[$field]);
899 DBA::update('item', $item_fields, ['id' => $item['id']]);
901 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
902 DBA::delete('item-content', ['id' => $item['icid']]);
905 } elseif (!empty($item['icid'])) {
906 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
908 if (!DBA::exists('item', ['icid' => $item['icid']])) {
909 DBA::delete('item-content', ['id' => $item['icid']]);
913 if (!empty($item['icid'])) {
914 $update_condition = ['id' => $item['icid']];
916 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
918 self::updateContent($content_fields, $update_condition);
920 if (empty($item['icid'])) {
921 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
922 if (DBA::isResult($item_content)) {
923 $item_fields = ['icid' => $item_content['id']];
924 // Clear all fields in the item table that have a content in the item-content table
925 foreach ($item_content as $field => $content) {
926 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
927 if (self::isLegacyMode()) {
928 $item_fields[$field] = null;
930 unset($item_fields[$field]);
934 DBA::update('item', $item_fields, ['id' => $item['id']]);
940 Term::insertFromTagFieldByItemId($item['id'], $tags);
941 if (!empty($item['tag'])) {
942 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
946 if (!empty($files)) {
947 Term::insertFromFileFieldByItemId($item['id'], $files);
948 if (!empty($item['file'])) {
949 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
953 self::updateDeliveryData($item['id'], $delivery_data);
955 self::updateThread($item['id']);
957 // We only need to notfiy others when it is an original entry from us.
958 // Only call the notifier when the item has some content relevant change.
959 if ($item['origin'] && in_array('edited', array_keys($fields))) {
960 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
970 * @brief Delete an item and notify others about it - if it was ours
972 * @param array $condition The condition for finding the item entries
973 * @param integer $priority Priority for the notification
975 public static function delete($condition, $priority = PRIORITY_HIGH)
977 $items = self::select(['id'], $condition);
978 while ($item = self::fetch($items)) {
979 self::deleteById($item['id'], $priority);
985 * @brief Delete an item for an user and notify others about it - if it was ours
987 * @param array $condition The condition for finding the item entries
988 * @param integer $uid User who wants to delete this item
990 public static function deleteForUser($condition, $uid)
996 $items = self::select(['id', 'uid'], $condition);
997 while ($item = self::fetch($items)) {
998 // "Deleting" global items just means hiding them
999 if ($item['uid'] == 0) {
1000 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1001 } elseif ($item['uid'] == $uid) {
1002 self::deleteById($item['id'], PRIORITY_HIGH);
1004 logger('Wrong ownership. Not deleting item ' . $item['id']);
1011 * @brief Delete an item and notify others about it - if it was ours
1013 * @param integer $item_id Item ID that should be delete
1014 * @param integer $priority Priority for the notification
1016 * @return boolean success
1018 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
1020 // locate item to be deleted
1021 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1022 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1023 'verb', 'object-type', 'object', 'target', 'contact-id',
1024 'icid', 'iaid', 'psid'];
1025 $item = self::selectFirst($fields, ['id' => $item_id]);
1026 if (!DBA::isResult($item)) {
1027 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
1031 if ($item['deleted']) {
1032 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
1036 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1037 if (!DBA::isResult($parent)) {
1038 $parent = ['origin' => false];
1041 // clean up categories and tags so they don't end up as orphans
1044 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1046 foreach ($matches as $mtch) {
1047 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1053 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1055 foreach ($matches as $mtch) {
1056 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1061 * If item is a link to a photo resource, nuke all the associated photos
1062 * (visitors will not have photo resources)
1063 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1064 * generate a resource-id and therefore aren't intimately linked to the item.
1066 if (strlen($item['resource-id'])) {
1067 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1070 // If item is a link to an event, delete the event.
1071 if (intval($item['event-id'])) {
1072 Event::delete($item['event-id']);
1075 // If item has attachments, drop them
1076 foreach (explode(", ", $item['attach']) as $attach) {
1077 preg_match("|attach/(\d+)|", $attach, $matches);
1078 if (is_array($matches) && count($matches) > 1) {
1079 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1083 // Delete tags that had been attached to other items
1084 self::deleteTagsFromItem($item);
1086 // Set the item to "deleted"
1087 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1088 DBA::update('item', $item_fields, ['id' => $item['id']]);
1090 Term::insertFromTagFieldByItemId($item['id'], '');
1091 Term::insertFromFileFieldByItemId($item['id'], '');
1092 self::deleteThread($item['id'], $item['parent-uri']);
1094 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1095 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1098 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1100 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1102 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1103 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1105 // When the permission set will be used in photo and events as well,
1106 // this query here needs to be extended.
1107 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1108 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1111 // If it's the parent of a comment thread, kill all the kids
1112 if ($item['id'] == $item['parent']) {
1113 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1116 // Is it our comment and/or our thread?
1117 if ($item['origin'] || $parent['origin']) {
1119 // When we delete the original post we will delete all existing copies on the server as well
1120 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1122 // send the notification upstream/downstream
1123 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1124 } elseif ($item['uid'] != 0) {
1126 // When we delete just our local user copy of an item, we have to set a marker to hide it
1127 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1128 if (DBA::isResult($global_item)) {
1129 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1133 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1138 private static function deleteTagsFromItem($item)
1140 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1144 $xo = XML::parseString($item["object"], false);
1145 $xt = XML::parseString($item["target"], false);
1147 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1151 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1152 if (!DBA::isResult($i)) {
1156 // For tags, the owner cannot remove the tag on the author's copy of the post.
1157 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1158 $author_copy = $item["origin"];
1160 if (($owner_remove && $author_copy) || !$owner_remove) {
1164 $tags = explode(',', $i["tag"]);
1167 foreach ($tags as $tag) {
1168 if (trim($tag) !== trim($xo->body)) {
1169 $newtags[] = trim($tag);
1173 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1176 private static function guid($item, $notify)
1178 if (!empty($item['guid'])) {
1179 return notags(trim($item['guid']));
1183 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1184 // We add the hash of our own host because our host is the original creator of the post.
1185 $prefix_host = get_app()->getHostName();
1189 // We are only storing the post so we create a GUID from the original hostname.
1190 if (!empty($item['author-link'])) {
1191 $parsed = parse_url($item['author-link']);
1192 if (!empty($parsed['host'])) {
1193 $prefix_host = $parsed['host'];
1197 if (empty($prefix_host) && !empty($item['plink'])) {
1198 $parsed = parse_url($item['plink']);
1199 if (!empty($parsed['host'])) {
1200 $prefix_host = $parsed['host'];
1204 if (empty($prefix_host) && !empty($item['uri'])) {
1205 $parsed = parse_url($item['uri']);
1206 if (!empty($parsed['host'])) {
1207 $prefix_host = $parsed['host'];
1211 // Is it in the format data@host.tld? - Used for mail contacts
1212 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1213 $mailparts = explode('@', $item['author-link']);
1214 $prefix_host = array_pop($mailparts);
1218 if (!empty($item['plink'])) {
1219 $guid = self::guidFromUri($item['plink'], $prefix_host);
1220 } elseif (!empty($item['uri'])) {
1221 $guid = self::guidFromUri($item['uri'], $prefix_host);
1223 $guid = System::createUUID(hash('crc32', $prefix_host));
1229 private static function contactId($item)
1231 $contact_id = (int)$item["contact-id"];
1233 if (!empty($contact_id)) {
1236 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1238 * First we are looking for a suitable contact that matches with the author of the post
1239 * This is done only for comments
1241 if ($item['parent-uri'] != $item['uri']) {
1242 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1245 // If not present then maybe the owner was found
1246 if ($contact_id == 0) {
1247 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1250 // Still missing? Then use the "self" contact of the current user
1251 if ($contact_id == 0) {
1252 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1253 if (DBA::isResult($self)) {
1254 $contact_id = $self["id"];
1257 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1262 // This function will finally cover most of the preparation functionality in mod/item.php
1263 public static function prepare(&$item)
1265 $data = BBCode::getAttachmentData($item['body']);
1266 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1267 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1268 $posttype = Item::PT_PAGE;
1269 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1273 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1277 // If it is a posting where users should get notifications, then define it as wall posting
1280 $item['origin'] = 1;
1281 $item['network'] = Protocol::DFRN;
1282 $item['protocol'] = Conversation::PARCEL_DFRN;
1284 if (is_int($notify)) {
1285 $priority = $notify;
1287 $priority = PRIORITY_HIGH;
1290 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1293 $item['guid'] = self::guid($item, $notify);
1294 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1297 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1299 // Store conversation data
1300 $item = Conversation::insert($item);
1303 * If a Diaspora signature structure was passed in, pull it out of the
1304 * item array and set it aside for later storage.
1308 if (isset($item['dsprsig'])) {
1309 $encoded_signature = $item['dsprsig'];
1310 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1311 unset($item['dsprsig']);
1314 $diaspora_signed_text = '';
1315 if (isset($item['diaspora_signed_text'])) {
1316 $diaspora_signed_text = $item['diaspora_signed_text'];
1317 unset($item['diaspora_signed_text']);
1320 // Converting the plink
1321 /// @TODO Check if this is really still needed
1322 if ($item['network'] == Protocol::OSTATUS) {
1323 if (isset($item['plink'])) {
1324 $item['plink'] = OStatus::convertHref($item['plink']);
1325 } elseif (isset($item['uri'])) {
1326 $item['plink'] = OStatus::convertHref($item['uri']);
1330 if (!empty($item['thr-parent'])) {
1331 $item['parent-uri'] = $item['thr-parent'];
1334 if (isset($item['gravity'])) {
1335 $item['gravity'] = intval($item['gravity']);
1336 } elseif ($item['parent-uri'] === $item['uri']) {
1337 $item['gravity'] = GRAVITY_PARENT;
1338 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1339 $item['gravity'] = GRAVITY_COMMENT;
1341 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1342 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1345 $uid = intval($item['uid']);
1347 // check for create date and expire time
1348 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1350 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1351 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1352 $expire_interval = $user['expire'];
1355 if (($expire_interval > 0) && !empty($item['created'])) {
1356 $expire_date = time() - ($expire_interval * 86400);
1357 $created_date = strtotime($item['created']);
1358 if ($created_date < $expire_date) {
1359 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1365 * Do we already have this item?
1366 * We have to check several networks since Friendica posts could be repeated
1367 * via OStatus (maybe Diasporsa as well)
1369 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1370 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1371 trim($item['uri']), $item['uid'],
1372 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1373 $existing = self::selectFirst(['id', 'network'], $condition);
1374 if (DBA::isResult($existing)) {
1375 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1377 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1380 return $existing["id"];
1384 // Ensure to always have the same creation date.
1385 $existing = self::selectfirst(['created', 'uri-hash'], ['uri' => $item['uri']]);
1386 if (DBA::isResult($existing)) {
1387 $item['created'] = $existing['created'];
1388 $item['uri-hash'] = $existing['uri-hash'];
1391 $item['wall'] = intval(defaults($item, 'wall', 0));
1392 $item['extid'] = trim(defaults($item, 'extid', ''));
1393 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1394 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1395 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1396 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1397 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1398 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1399 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1400 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1401 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1402 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1403 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1404 $item['title'] = trim(defaults($item, 'title', ''));
1405 $item['location'] = trim(defaults($item, 'location', ''));
1406 $item['coord'] = trim(defaults($item, 'coord', ''));
1407 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1408 $item['deleted'] = 0;
1409 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1410 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1411 $item['verb'] = trim(defaults($item, 'verb', ''));
1412 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1413 $item['object'] = trim(defaults($item, 'object', ''));
1414 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1415 $item['target'] = trim(defaults($item, 'target', ''));
1416 $item['plink'] = trim(defaults($item, 'plink', ''));
1417 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1418 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1419 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1420 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1421 $item['private'] = intval(defaults($item, 'private', 0));
1422 $item['body'] = trim(defaults($item, 'body', ''));
1423 $item['tag'] = trim(defaults($item, 'tag', ''));
1424 $item['attach'] = trim(defaults($item, 'attach', ''));
1425 $item['app'] = trim(defaults($item, 'app', ''));
1426 $item['origin'] = intval(defaults($item, 'origin', 0));
1427 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1428 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1429 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1430 $item['inform'] = trim(defaults($item, 'inform', ''));
1431 $item['file'] = trim(defaults($item, 'file', ''));
1433 // Unique identifier to be linked against item-activities and item-content
1434 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1436 // When there is no content then we don't post it
1437 if ($item['body'].$item['title'] == '') {
1438 logger('No body, no title.');
1442 self::addLanguageToItemArray($item);
1444 // Items cannot be stored before they happen ...
1445 if ($item['created'] > DateTimeFormat::utcNow()) {
1446 $item['created'] = DateTimeFormat::utcNow();
1449 // We haven't invented time travel by now.
1450 if ($item['edited'] > DateTimeFormat::utcNow()) {
1451 $item['edited'] = DateTimeFormat::utcNow();
1454 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1456 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1457 $item["contact-id"] = self::contactId($item);
1459 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1460 'photo' => $item['author-avatar'], 'network' => $item['network']];
1462 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1464 if (Contact::isBlocked($item["author-id"])) {
1465 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1469 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1470 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1472 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1474 if (Contact::isBlocked($item["owner-id"])) {
1475 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1479 if ($item['network'] == Protocol::PHANTOM) {
1480 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1482 $item['network'] = Protocol::DFRN;
1483 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1486 // Checking if there is already an item with the same guid
1487 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1488 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1489 if (self::exists($condition)) {
1490 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1494 // Check for hashtags in the body and repair or add hashtag links
1495 self::setHashtags($item);
1497 $item['thr-parent'] = $item['parent-uri'];
1505 if ($item['parent-uri'] === $item['uri']) {
1507 $parent_deleted = 0;
1508 $allow_cid = $item['allow_cid'];
1509 $allow_gid = $item['allow_gid'];
1510 $deny_cid = $item['deny_cid'];
1511 $deny_gid = $item['deny_gid'];
1512 $notify_type = 'wall-new';
1514 // find the parent and snarf the item id and ACLs
1515 // and anything else we need to inherit
1517 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1518 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1519 'wall', 'private', 'forum_mode', 'origin'];
1520 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1521 $params = ['order' => ['id' => false]];
1522 $parent = self::selectFirst($fields, $condition, $params);
1524 if (DBA::isResult($parent)) {
1525 // is the new message multi-level threaded?
1526 // even though we don't support it now, preserve the info
1527 // and re-attach to the conversation parent.
1529 if ($parent['uri'] != $parent['parent-uri']) {
1530 $item['parent-uri'] = $parent['parent-uri'];
1532 $condition = ['uri' => $item['parent-uri'],
1533 'parent-uri' => $item['parent-uri'],
1534 'uid' => $item['uid']];
1535 $params = ['order' => ['id' => false]];
1536 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1538 if (DBA::isResult($toplevel_parent)) {
1539 $parent = $toplevel_parent;
1543 $parent_id = $parent['id'];
1544 $parent_deleted = $parent['deleted'];
1545 $allow_cid = $parent['allow_cid'];
1546 $allow_gid = $parent['allow_gid'];
1547 $deny_cid = $parent['deny_cid'];
1548 $deny_gid = $parent['deny_gid'];
1549 $item['wall'] = $parent['wall'];
1550 $notify_type = 'comment-new';
1553 * If the parent is private, force privacy for the entire conversation
1554 * This differs from the above settings as it subtly allows comments from
1555 * email correspondents to be private even if the overall thread is not.
1557 if ($parent['private']) {
1558 $item['private'] = $parent['private'];
1562 * Edge case. We host a public forum that was originally posted to privately.
1563 * The original author commented, but as this is a comment, the permissions
1564 * weren't fixed up so it will still show the comment as private unless we fix it here.
1566 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1567 $item['private'] = 0;
1570 // If its a post from myself then tag the thread as "mention"
1571 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1572 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1573 if (DBA::isResult($user)) {
1574 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1575 $self_id = Contact::getIdForURL($self, 0, true);
1576 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1577 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1578 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1579 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1584 * Allow one to see reply tweets from status.net even when
1585 * we don't have or can't see the original post.
1587 if ($force_parent) {
1588 logger('$force_parent=true, reply converted to top-level post.');
1590 $item['parent-uri'] = $item['uri'];
1591 $item['gravity'] = GRAVITY_PARENT;
1593 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1597 $parent_deleted = 0;
1601 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1602 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1604 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1605 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1606 if (self::exists($condition)) {
1607 logger('duplicated item with the same uri found. '.print_r($item,true));
1611 // On Friendica and Diaspora the GUID is unique
1612 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1613 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1614 if (self::exists($condition)) {
1615 logger('duplicated item with the same guid found. '.print_r($item,true));
1619 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1620 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1621 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1622 if (self::exists($condition)) {
1623 logger('duplicated item with the same body found. '.print_r($item,true));
1628 // Is this item available in the global items (with uid=0)?
1629 if ($item["uid"] == 0) {
1630 $item["global"] = true;
1632 // Set the global flag on all items if this was a global item entry
1633 self::update(['global' => true], ['uri' => $item["uri"]]);
1635 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1639 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1642 $private = $item['private'];
1645 $item["allow_cid"] = $allow_cid;
1646 $item["allow_gid"] = $allow_gid;
1647 $item["deny_cid"] = $deny_cid;
1648 $item["deny_gid"] = $deny_gid;
1649 $item["private"] = $private;
1650 $item["deleted"] = $parent_deleted;
1652 // Fill the cache field
1653 put_item_in_cache($item);
1656 $item['edit'] = false;
1657 $item['parent'] = $parent_id;
1658 Addon::callHooks('post_local', $item);
1659 unset($item['edit']);
1660 unset($item['parent']);
1662 Addon::callHooks('post_remote', $item);
1665 // This array field is used to trigger some automatic reactions
1666 // It is mainly used in the "post_local" hook.
1667 unset($item['api_source']);
1669 if (x($item, 'cancel')) {
1670 logger('post cancelled by addon.');
1675 * Check for already added items.
1676 * There is a timing issue here that sometimes creates double postings.
1677 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1679 if ($item["uid"] == 0) {
1680 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1681 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1686 logger('' . print_r($item,true), LOGGER_DATA);
1688 if (array_key_exists('tag', $item)) {
1689 $tags = $item['tag'];
1690 unset($item['tag']);
1695 if (array_key_exists('file', $item)) {
1696 $files = $item['file'];
1697 unset($item['file']);
1702 // Creates or assigns the permission set
1703 $item['psid'] = PermissionSet::fetchIDForPost($item);
1705 // We are doing this outside of the transaction to avoid timing problems
1706 if (!self::insertActivity($item)) {
1707 self::insertContent($item);
1710 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1711 'inform' => defaults($item, 'inform', '')];
1713 unset($item['postopts']);
1714 unset($item['inform']);
1716 // These fields aren't stored anymore in the item table, they are fetched upon request
1717 unset($item['author-link']);
1718 unset($item['author-name']);
1719 unset($item['author-avatar']);
1721 unset($item['owner-link']);
1722 unset($item['owner-name']);
1723 unset($item['owner-avatar']);
1726 $ret = DBA::insert('item', $item);
1728 // When the item was successfully stored we fetch the ID of the item.
1729 if (DBA::isResult($ret)) {
1730 $current_post = DBA::lastInsertId();
1732 // This can happen - for example - if there are locking timeouts.
1735 // Store the data into a spool file so that we can try again later.
1737 // At first we restore the Diaspora signature that we removed above.
1738 if (isset($encoded_signature)) {
1739 $item['dsprsig'] = $encoded_signature;
1742 // Now we store the data in the spool directory
1743 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1744 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1746 $spoolpath = get_spoolpath();
1747 if ($spoolpath != "") {
1748 $spool = $spoolpath.'/'.$file;
1750 // Ensure to have the removed data from above again in the item array
1751 $item = array_merge($item, $delivery_data);
1753 file_put_contents($spool, json_encode($item));
1754 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1759 if ($current_post == 0) {
1760 // This is one of these error messages that never should occur.
1761 logger("couldn't find created item - we better quit now.");
1766 // How much entries have we created?
1767 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1768 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1771 // There are duplicates. We delete our just created entry.
1772 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1774 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1775 DBA::delete('item', ['id' => $current_post]);
1778 } elseif ($entries == 0) {
1779 // This really should never happen since we quit earlier if there were problems.
1780 logger("Something is terribly wrong. We haven't found our created entry.");
1785 logger('created item '.$current_post);
1786 self::updateContact($item);
1788 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1789 $parent_id = $current_post;
1793 self::update(['parent' => $parent_id], ['id' => $current_post]);
1795 $item['id'] = $current_post;
1796 $item['parent'] = $parent_id;
1798 // update the commented timestamp on the parent
1799 // Only update "commented" if it is really a comment
1800 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1801 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1803 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1808 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1809 * We can check for this condition when we decode and encode the stuff again.
1811 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1812 $dsprsig->signature = base64_decode($dsprsig->signature);
1813 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1816 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1817 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1819 // The other fields are used by very old Friendica servers, so we currently store them differently
1820 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1821 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1825 if (!empty($diaspora_signed_text)) {
1826 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1829 $deleted = self::tagDeliver($item['uid'], $current_post);
1832 * current post can be deleted if is for a community page and no mention are
1835 if (!$deleted && !$dontcache) {
1836 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1837 if (DBA::isResult($posted_item)) {
1839 Addon::callHooks('post_local_end', $posted_item);
1841 Addon::callHooks('post_remote_end', $posted_item);
1844 logger('new item not found in DB, id ' . $current_post);
1848 if ($item['parent-uri'] === $item['uri']) {
1849 self::addThread($current_post);
1851 self::updateThread($parent_id);
1854 $delivery_data['iid'] = $current_post;
1856 self::insertDeliveryData($delivery_data);
1861 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1862 * This is not perfect - but a workable solution until we found the reason for the problem.
1864 if (!empty($tags)) {
1865 Term::insertFromTagFieldByItemId($current_post, $tags);
1868 if (!empty($files)) {
1869 Term::insertFromFileFieldByItemId($current_post, $files);
1872 if ($item['parent-uri'] === $item['uri']) {
1873 self::addShadow($current_post);
1875 self::addShadowPost($current_post);
1878 check_user_notification($current_post);
1881 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1882 } elseif (!empty($parent) && $parent['origin']) {
1883 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1886 return $current_post;
1890 * @brief Insert a new item delivery data entry
1892 * @param array $item The item fields that are to be inserted
1894 private static function insertDeliveryData($delivery_data)
1896 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1900 DBA::insert('item-delivery-data', $delivery_data);
1904 * @brief Update an existing item delivery data entry
1906 * @param integer $id The item id that is to be updated
1907 * @param array $item The item fields that are to be inserted
1909 private static function updateDeliveryData($id, $delivery_data)
1911 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1915 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1919 * @brief Insert a new item content entry
1921 * @param array $item The item fields that are to be inserted
1923 private static function insertActivity(&$item)
1925 $activity_index = self::activityToIndex($item['verb']);
1927 if ($activity_index < 0) {
1931 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1932 'uri-hash' => $item['uri-hash'], 'uri-id' => $item['uri-id']];
1934 // We just remove everything that is content
1935 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1936 unset($item[$field]);
1939 // To avoid timing problems, we are using locks.
1940 $locked = Lock::acquire('item_insert_activity');
1942 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1945 // Do we already have this content?
1946 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1947 if (DBA::isResult($item_activity)) {
1948 $item['iaid'] = $item_activity['id'];
1949 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1950 } elseif (DBA::insert('item-activity', $fields)) {
1951 $item['iaid'] = DBA::lastInsertId();
1952 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1954 // This shouldn't happen.
1955 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1956 Lock::release('item_insert_activity');
1960 Lock::release('item_insert_activity');
1966 * @brief Insert a new item content entry
1968 * @param array $item The item fields that are to be inserted
1970 private static function insertContent(&$item)
1972 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash'],
1973 'uri-id' => $item['uri-id']];
1975 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1976 if (isset($item[$field])) {
1977 $fields[$field] = $item[$field];
1978 unset($item[$field]);
1982 // To avoid timing problems, we are using locks.
1983 $locked = Lock::acquire('item_insert_content');
1985 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1988 // Do we already have this content?
1989 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1990 if (DBA::isResult($item_content)) {
1991 $item['icid'] = $item_content['id'];
1992 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1993 } elseif (DBA::insert('item-content', $fields)) {
1994 $item['icid'] = DBA::lastInsertId();
1995 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1997 // This shouldn't happen.
1998 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2001 Lock::release('item_insert_content');
2006 * @brief Update existing item content entries
2008 * @param array $item The item fields that are to be changed
2009 * @param array $condition The condition for finding the item content entries
2011 private static function updateActivity($item, $condition)
2013 if (empty($item['verb'])) {
2016 $activity_index = self::activityToIndex($item['verb']);
2018 if ($activity_index < 0) {
2022 $fields = ['activity' => $activity_index];
2024 logger('Update activity for ' . json_encode($condition));
2026 DBA::update('item-activity', $fields, $condition, true);
2032 * @brief Update existing item content entries
2034 * @param array $item The item fields that are to be changed
2035 * @param array $condition The condition for finding the item content entries
2037 private static function updateContent($item, $condition)
2039 // We have to select only the fields from the "item-content" table
2041 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2042 if (isset($item[$field])) {
2043 $fields[$field] = $item[$field];
2047 if (empty($fields)) {
2048 // when there are no fields at all, just use the condition
2049 // This is to ensure that we always store content.
2050 $fields = $condition;
2053 logger('Update content for ' . json_encode($condition));
2055 DBA::update('item-content', $fields, $condition, true);
2059 * @brief Distributes public items to the receivers
2061 * @param integer $itemid Item ID that should be added
2062 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2064 public static function distribute($itemid, $signed_text = '')
2066 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2067 $parent = self::selectFirst(['owner-id'], $condition);
2068 if (!DBA::isResult($parent)) {
2072 // Only distribute public items from native networks
2073 $condition = ['id' => $itemid, 'uid' => 0,
2074 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2075 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2076 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2077 if (!DBA::isResult($item)) {
2081 $origin = $item['origin'];
2084 unset($item['parent']);
2085 unset($item['mention']);
2086 unset($item['wall']);
2087 unset($item['origin']);
2088 unset($item['starred']);
2092 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2093 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2094 if (!DBA::isResult($owner)) {
2098 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2099 $contacts = DBA::select('contact', ['uid'], $condition);
2100 while ($contact = DBA::fetch($contacts)) {
2101 if ($contact['uid'] == 0) {
2105 $users[$contact['uid']] = $contact['uid'];
2107 DBA::close($contacts);
2109 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2110 $contacts = DBA::select('contact', ['uid'], $condition);
2111 while ($contact = DBA::fetch($contacts)) {
2112 if ($contact['uid'] == 0) {
2116 $users[$contact['uid']] = $contact['uid'];
2118 DBA::close($contacts);
2120 if (!empty($owner['alias'])) {
2121 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2122 $contacts = DBA::select('contact', ['uid'], $condition);
2123 while ($contact = DBA::fetch($contacts)) {
2124 if ($contact['uid'] == 0) {
2128 $users[$contact['uid']] = $contact['uid'];
2130 DBA::close($contacts);
2135 if ($item['uri'] != $item['parent-uri']) {
2136 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2137 while ($parent = self::fetch($parents)) {
2138 $users[$parent['uid']] = $parent['uid'];
2139 if ($parent['origin'] && !$origin) {
2140 $origin_uid = $parent['uid'];
2145 foreach ($users as $uid) {
2146 if ($origin_uid == $uid) {
2147 $item['diaspora_signed_text'] = $signed_text;
2149 self::storeForUser($itemid, $item, $uid);
2154 * @brief Store public items for the receivers
2156 * @param integer $itemid Item ID that should be added
2157 * @param array $item The item entry that will be stored
2158 * @param integer $uid The user that will receive the item entry
2160 private static function storeForUser($itemid, $item, $uid)
2162 $item['uid'] = $uid;
2163 $item['origin'] = 0;
2165 if ($item['uri'] == $item['parent-uri']) {
2166 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2168 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2171 if (empty($item['contact-id'])) {
2172 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2173 if (!DBA::isResult($self)) {
2176 $item['contact-id'] = $self['id'];
2179 /// @todo Handling of "event-id"
2182 if ($item['uri'] == $item['parent-uri']) {
2183 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2184 if (DBA::isResult($contact)) {
2185 $notify = self::isRemoteSelf($contact, $item);
2189 $distributed = self::insert($item, false, $notify, true);
2191 if (!$distributed) {
2192 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2194 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2199 * @brief Add a shadow entry for a given item id that is a thread starter
2201 * We store every public item entry additionally with the user id "0".
2202 * This is used for the community page and for the search.
2203 * It is planned that in the future we will store public item entries only once.
2205 * @param integer $itemid Item ID that should be added
2207 public static function addShadow($itemid)
2209 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2210 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2211 $item = self::selectFirst($fields, $condition);
2213 if (!DBA::isResult($item)) {
2217 // is it already a copy?
2218 if (($itemid == 0) || ($item['uid'] == 0)) {
2222 // Is it a visible public post?
2223 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2227 // is it an entry from a connector? Only add an entry for natively connected networks
2228 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2232 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2236 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2238 if (DBA::isResult($item)) {
2239 // Preparing public shadow (removing user specific data)
2242 unset($item['parent']);
2243 unset($item['wall']);
2244 unset($item['mention']);
2245 unset($item['origin']);
2246 unset($item['starred']);
2247 unset($item['postopts']);
2248 unset($item['inform']);
2249 if ($item['uri'] == $item['parent-uri']) {
2250 $item['contact-id'] = $item['owner-id'];
2252 $item['contact-id'] = $item['author-id'];
2255 $public_shadow = self::insert($item, false, false, true);
2257 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2262 * @brief Add a shadow entry for a given item id that is a comment
2264 * This function does the same like the function above - but for comments
2266 * @param integer $itemid Item ID that should be added
2268 public static function addShadowPost($itemid)
2270 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2271 if (!DBA::isResult($item)) {
2275 // Is it a toplevel post?
2276 if ($item['id'] == $item['parent']) {
2277 self::addShadow($itemid);
2281 // Is this a shadow entry?
2282 if ($item['uid'] == 0) {
2286 // Is there a shadow parent?
2287 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2291 // Is there already a shadow entry?
2292 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2296 // Save "origin" and "parent" state
2297 $origin = $item['origin'];
2298 $parent = $item['parent'];
2300 // Preparing public shadow (removing user specific data)
2303 unset($item['parent']);
2304 unset($item['wall']);
2305 unset($item['mention']);
2306 unset($item['origin']);
2307 unset($item['starred']);
2308 unset($item['postopts']);
2309 unset($item['inform']);
2310 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2312 $public_shadow = self::insert($item, false, false, true);
2314 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2316 // If this was a comment to a Diaspora post we don't get our comment back.
2317 // This means that we have to distribute the comment by ourselves.
2318 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2319 self::distribute($public_shadow);
2324 * Adds a language specification in a "language" element of given $arr.
2325 * Expects "body" element to exist in $arr.
2327 private static function addLanguageToItemArray(&$item)
2329 $naked_body = BBCode::toPlaintext($item['body'], false);
2331 $ld = new Text_LanguageDetect();
2332 $ld->setNameMode(2);
2333 $languages = $ld->detect($naked_body, 3);
2335 if (is_array($languages)) {
2336 $item['language'] = json_encode($languages);
2341 * @brief Creates an unique guid out of a given uri
2343 * @param string $uri uri of an item entry
2344 * @param string $host hostname for the GUID prefix
2345 * @return string unique guid
2347 public static function guidFromUri($uri, $host)
2349 // Our regular guid routine is using this kind of prefix as well
2350 // We have to avoid that different routines could accidentally create the same value
2351 $parsed = parse_url($uri);
2353 // We use a hash of the hostname as prefix for the guid
2354 $guid_prefix = hash("crc32", $host);
2356 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2357 unset($parsed["scheme"]);
2359 // Glue it together to be able to make a hash from it
2360 $host_id = implode("/", $parsed);
2362 // We could use any hash algorithm since it isn't a security issue
2363 $host_hash = hash("ripemd128", $host_id);
2365 return $guid_prefix.$host_hash;
2369 * generate an unique URI
2371 * @param integer $uid User id
2372 * @param string $guid An existing GUID (Otherwise it will be generated)
2376 public static function newURI($uid, $guid = "")
2379 $guid = System::createUUID();
2382 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2386 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2388 * This can be used to filter for inactive contacts.
2389 * Only do this for public postings to avoid privacy problems, since poco data is public.
2390 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2392 * @param array $arr Contains the just posted item record
2394 private static function updateContact($arr)
2396 // Unarchive the author
2397 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2398 if (DBA::isResult($contact)) {
2399 Contact::unmarkForArchival($contact);
2402 // Unarchive the contact if it's not our own contact
2403 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2404 if (DBA::isResult($contact)) {
2405 Contact::unmarkForArchival($contact);
2408 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2410 // Is it a forum? Then we don't care about the rules from above
2411 if (!$update && ($arr["network"] == Protocol::DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2412 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2418 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2419 ['id' => $arr['contact-id']]);
2421 // Now do the same for the system wide contacts with uid=0
2422 if (!$arr['private']) {
2423 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2424 ['id' => $arr['owner-id']]);
2426 if ($arr['owner-id'] != $arr['author-id']) {
2427 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2428 ['id' => $arr['author-id']]);
2433 public static function setHashtags(&$item)
2436 $tags = get_tags($item["body"]);
2439 if (!count($tags)) {
2443 // This sorting is important when there are hashtags that are part of other hashtags
2444 // Otherwise there could be problems with hashtags like #test and #test2
2447 $URLSearchString = "^\[\]";
2449 // All hashtags should point to the home server if "local_tags" is activated
2450 if (Config::get('system', 'local_tags')) {
2451 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2452 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2454 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2455 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2458 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2459 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2461 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2464 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2466 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2469 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2471 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2474 // Repair recursive urls
2475 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2476 "#$2", $item["body"]);
2478 foreach ($tags as $tag) {
2479 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2483 $basetag = str_replace('_',' ',substr($tag,1));
2485 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2487 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2489 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2490 if (strlen($item["tag"])) {
2491 $item["tag"] = ','.$item["tag"];
2493 $item["tag"] = $newtag.$item["tag"];
2497 // Convert back the masked hashtags
2498 $item["body"] = str_replace("#", "#", $item["body"]);
2501 public static function getGuidById($id)
2503 $item = self::selectFirst(['guid'], ['id' => $id]);
2504 if (DBA::isResult($item)) {
2505 return $item['guid'];
2512 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2513 * @param string $guid item guid
2514 * @param int $uid user id
2515 * @return array with id and nick of the item with the given guid
2517 public static function getIdAndNickByGuid($guid, $uid = 0)
2523 $uid == local_user();
2526 // Does the given user have this item?
2528 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2529 if (DBA::isResult($item)) {
2530 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2531 if (!DBA::isResult($user)) {
2535 $nick = $user['nickname'];
2539 // Or is it anywhere on the server?
2541 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2542 $item = self::selectFirst(['id', 'uid'], $condition);
2543 if (DBA::isResult($item)) {
2544 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2545 if (!DBA::isResult($user)) {
2549 $nick = $user['nickname'];
2552 return ["nick" => $nick, "id" => $id];
2556 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2558 * @param int $item_id
2559 * @return bool true if item was deleted, else false
2561 private static function tagDeliver($uid, $item_id)
2565 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2566 if (!DBA::isResult($user)) {
2570 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2571 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2573 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2574 if (!DBA::isResult($item)) {
2578 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2581 * Diaspora uses their own hardwired link URL in @-tags
2582 * instead of the one we supply with webfinger
2584 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2586 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2588 foreach ($matches as $mtch) {
2589 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2591 logger('mention found: ' . $mtch[2]);
2597 if (($community_page || $prvgroup) &&
2598 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2599 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2601 logger("no-mention top-level post to community or private group. delete.");
2602 DBA::delete('item', ['id' => $item_id]);
2608 $arr = ['item' => $item, 'user' => $user];
2610 Addon::callHooks('tagged', $arr);
2612 if (!$community_page && !$prvgroup) {
2617 * tgroup delivery - setup a second delivery chain
2618 * prevent delivery looping - only proceed
2619 * if the message originated elsewhere and is a top-level post
2621 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2625 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2626 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2627 if (!DBA::isResult($self)) {
2631 $owner_id = Contact::getIdForURL($self['url']);
2633 // also reset all the privacy bits to the forum default permissions
2635 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2637 $psid = PermissionSet::fetchIDForPost($user);
2639 $forum_mode = ($prvgroup ? 2 : 1);
2641 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2642 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2643 self::update($fields, ['id' => $item_id]);
2645 self::updateThread($item_id);
2647 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2650 public static function isRemoteSelf($contact, &$datarray)
2654 if (!$contact['remote_self']) {
2658 // Prevent the forwarding of posts that are forwarded
2659 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2660 logger('Already forwarded', LOGGER_DEBUG);
2664 // Prevent to forward already forwarded posts
2665 if ($datarray["app"] == $a->getHostName()) {
2666 logger('Already forwarded (second test)', LOGGER_DEBUG);
2670 // Only forward posts
2671 if ($datarray["verb"] != ACTIVITY_POST) {
2672 logger('No post', LOGGER_DEBUG);
2676 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2677 logger('Not public', LOGGER_DEBUG);
2681 $datarray2 = $datarray;
2682 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2683 if ($contact['remote_self'] == 2) {
2684 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2685 ['uid' => $contact['uid'], 'self' => true]);
2686 if (DBA::isResult($self)) {
2687 $datarray['contact-id'] = $self["id"];
2689 $datarray['owner-name'] = $self["name"];
2690 $datarray['owner-link'] = $self["url"];
2691 $datarray['owner-avatar'] = $self["thumb"];
2693 $datarray['author-name'] = $datarray['owner-name'];
2694 $datarray['author-link'] = $datarray['owner-link'];
2695 $datarray['author-avatar'] = $datarray['owner-avatar'];
2697 unset($datarray['created']);
2698 unset($datarray['edited']);
2700 unset($datarray['network']);
2701 unset($datarray['owner-id']);
2702 unset($datarray['author-id']);
2705 if ($contact['network'] != Protocol::FEED) {
2706 $datarray["guid"] = System::createUUID();
2707 unset($datarray["plink"]);
2708 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2709 $datarray["parent-uri"] = $datarray["uri"];
2710 $datarray["thr-parent"] = $datarray["uri"];
2711 $datarray["extid"] = Protocol::DFRN;
2712 $urlpart = parse_url($datarray2['author-link']);
2713 $datarray["app"] = $urlpart["host"];
2715 $datarray['private'] = 0;
2719 if ($contact['network'] != Protocol::FEED) {
2720 // Store the original post
2721 $result = self::insert($datarray2, false, false);
2722 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2724 $datarray["app"] = "Feed";
2728 // Trigger automatic reactions for addons
2729 $datarray['api_source'] = true;
2731 // We have to tell the hooks who we are - this really should be improved
2732 $_SESSION["authenticated"] = true;
2733 $_SESSION["uid"] = $contact['uid'];
2742 * @param array $item
2746 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2748 if (Config::get('system', 'disable_embedded')) {
2752 logger('check for photos', LOGGER_DEBUG);
2753 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2758 $img_start = strpos($orig_body, '[img');
2759 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2760 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2762 while (($img_st_close !== false) && ($img_len !== false)) {
2763 $img_st_close++; // make it point to AFTER the closing bracket
2764 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2766 logger('found photo ' . $image, LOGGER_DEBUG);
2768 if (stristr($image, $site . '/photo/')) {
2769 // Only embed locally hosted photos
2771 $i = basename($image);
2772 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2773 $x = strpos($i, '-');
2776 $res = substr($i, $x + 1);
2777 $i = substr($i, 0, $x);
2778 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2779 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2780 if (DBA::isResult($photo)) {
2782 * Check to see if we should replace this photo link with an embedded image
2783 * 1. No need to do so if the photo is public
2784 * 2. If there's a contact-id provided, see if they're in the access list
2785 * for the photo. If so, embed it.
2786 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2787 * permissions, regardless of order but first check to see if they're an exact
2788 * match to save some processing overhead.
2790 if (self::hasPermissions($photo)) {
2792 $recips = self::enumeratePermissions($photo);
2793 if (in_array($cid, $recips)) {
2797 if (self::samePermissions($item, $photo)) {
2803 $data = $photo['data'];
2804 $type = $photo['type'];
2806 // If a custom width and height were specified, apply before embedding
2807 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2808 logger('scaling photo', LOGGER_DEBUG);
2810 $width = intval($match[1]);
2811 $height = intval($match[2]);
2813 $Image = new Image($data, $type);
2814 if ($Image->isValid()) {
2815 $Image->scaleDown(max($width, $height));
2816 $data = $Image->asString();
2817 $type = $Image->getType();
2821 logger('replacing photo', LOGGER_DEBUG);
2822 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2823 logger('replaced: ' . $image, LOGGER_DATA);
2829 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2830 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2831 if ($orig_body === false) {
2835 $img_start = strpos($orig_body, '[img');
2836 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2837 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2840 $new_body = $new_body . $orig_body;
2845 private static function hasPermissions($obj)
2847 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2848 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2851 private static function samePermissions($obj1, $obj2)
2853 // first part is easy. Check that these are exactly the same.
2854 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2855 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2856 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2857 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2861 // This is harder. Parse all the permissions and compare the resulting set.
2862 $recipients1 = self::enumeratePermissions($obj1);
2863 $recipients2 = self::enumeratePermissions($obj2);
2867 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2868 return ($recipients1 == $recipients2);
2871 // returns an array of contact-ids that are allowed to see this object
2872 public static function enumeratePermissions($obj)
2874 $allow_people = expand_acl($obj['allow_cid']);
2875 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2876 $deny_people = expand_acl($obj['deny_cid']);
2877 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2878 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2879 $deny = array_unique(array_merge($deny_people, $deny_groups));
2880 $recipients = array_diff($recipients, $deny);
2884 public static function getFeedTags($item)
2888 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2890 for ($x = 0; $x < $cnt; $x ++) {
2891 if ($matches[1][$x]) {
2892 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2897 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2899 for ($x = 0; $x < $cnt; $x ++) {
2900 if ($matches[1][$x]) {
2901 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2908 public static function expire($uid, $days, $network = "", $force = false)
2910 if (!$uid || ($days < 1)) {
2914 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2915 $uid, GRAVITY_PARENT];
2918 * $expire_network_only = save your own wall posts
2919 * and just expire conversations started by others
2921 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2923 if ($expire_network_only) {
2924 $condition[0] .= " AND NOT `wall`";
2927 if ($network != "") {
2928 $condition[0] .= " AND `network` = ?";
2929 $condition[] = $network;
2932 * There is an index "uid_network_received" but not "uid_network_created"
2933 * This avoids the creation of another index just for one purpose.
2934 * And it doesn't really matter wether to look at "received" or "created"
2936 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2937 $condition[] = $days;
2939 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2940 $condition[] = $days;
2943 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2945 if (!DBA::isResult($items)) {
2949 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2951 // Forcing expiring of items - but not notes and marked items
2953 $expire_items = true;
2956 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2957 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2958 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2962 while ($item = Item::fetch($items)) {
2963 // don't expire filed items
2965 if (strpos($item['file'], '[') !== false) {
2969 // Only expire posts, not photos and photo comments
2971 if (!$expire_photos && strlen($item['resource-id'])) {
2973 } elseif (!$expire_starred && intval($item['starred'])) {
2975 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2977 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2981 self::deleteById($item['id'], PRIORITY_LOW);
2986 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2989 public static function firstPostDate($uid, $wall = false)
2991 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2992 $params = ['order' => ['created' => false]];
2993 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2994 if (DBA::isResult($thread)) {
2995 return substr(DateTimeFormat::local($thread['created']), 0, 10);
3001 * @brief add/remove activity to an item
3003 * Toggle activities as like,dislike,attend of an item
3005 * @param string $item_id
3006 * @param string $verb
3007 * Activity verb. One of
3008 * like, unlike, dislike, undislike, attendyes, unattendyes,
3009 * attendno, unattendno, attendmaybe, unattendmaybe
3010 * @hook 'post_local_end'
3012 * 'post_id' => ID of posted item
3014 public static function performLike($item_id, $verb)
3016 if (!local_user() && !remote_user()) {
3023 $activity = ACTIVITY_LIKE;
3027 $activity = ACTIVITY_DISLIKE;
3031 $activity = ACTIVITY_ATTEND;
3035 $activity = ACTIVITY_ATTENDNO;
3038 case 'unattendmaybe':
3039 $activity = ACTIVITY_ATTENDMAYBE;
3042 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
3046 // Enable activity toggling instead of on/off
3047 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3049 logger('like: verb ' . $verb . ' item ' . $item_id);
3051 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3052 if (!DBA::isResult($item)) {
3053 logger('like: unknown item ' . $item_id);
3057 $item_uri = $item['uri'];
3059 $uid = $item['uid'];
3060 if (($uid == 0) && local_user()) {
3061 $uid = local_user();
3064 if (!Security::canWriteToUserWall($uid)) {
3065 logger('like: unable to write on wall ' . $uid);
3069 // Retrieves the local post owner
3070 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3071 if (!DBA::isResult($owner_self_contact)) {
3072 logger('like: unknown owner ' . $uid);
3076 // Retrieve the current logged in user's public contact
3077 $author_id = public_contact();
3079 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3080 if (!DBA::isResult($author_contact)) {
3081 logger('like: unknown author ' . $author_id);
3085 // Contact-id is the uid-dependant author contact
3086 if (local_user() == $uid) {
3087 $item_contact_id = $owner_self_contact['id'];
3088 $item_contact = $owner_self_contact;
3090 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3091 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3092 if (!DBA::isResult($item_contact)) {
3093 logger('like: unknown item contact ' . $item_contact_id);
3098 // Look for an existing verb row
3099 // event participation are essentially radio toggles. If you make a subsequent choice,
3100 // we need to eradicate your first choice.
3101 if ($event_verb_flag) {
3102 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3104 // Translate to the index based activity index
3106 foreach ($verbs as $verb) {
3107 $activities[] = self::activityToIndex($verb);
3110 $activities = self::activityToIndex($activity);
3113 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3114 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3116 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3118 // If it exists, mark it as deleted
3119 if (DBA::isResult($like_item)) {
3120 self::deleteById($like_item['id']);
3122 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3127 // Verb is "un-something", just trying to delete existing entries
3128 if (strpos($verb, 'un') === 0) {
3132 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3135 'guid' => System::createUUID(),
3136 'uri' => self::newURI($item['uid']),
3137 'uid' => $item['uid'],
3138 'contact-id' => $item_contact_id,
3139 'wall' => $item['wall'],
3141 'network' => Protocol::DFRN,
3142 'gravity' => GRAVITY_ACTIVITY,
3143 'parent' => $item['id'],
3144 'parent-uri' => $item['uri'],
3145 'thr-parent' => $item['uri'],
3146 'owner-id' => $author_id,
3147 'author-id' => $author_id,
3148 'body' => $activity,
3149 'verb' => $activity,
3150 'object-type' => $objtype,
3151 'allow_cid' => $item['allow_cid'],
3152 'allow_gid' => $item['allow_gid'],
3153 'deny_cid' => $item['deny_cid'],
3154 'deny_gid' => $item['deny_gid'],
3159 $new_item_id = self::insert($new_item);
3161 // If the parent item isn't visible then set it to visible
3162 if (!$item['visible']) {
3163 self::update(['visible' => true], ['id' => $item['id']]);
3166 // Save the author information for the like in case we need to relay to Diaspora
3167 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3169 $new_item['id'] = $new_item_id;
3171 Addon::callHooks('post_local_end', $new_item);
3173 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3178 private static function addThread($itemid, $onlyshadow = false)
3180 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3181 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3182 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3183 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3184 $item = self::selectFirst($fields, $condition);
3186 if (!DBA::isResult($item)) {
3190 $item['iid'] = $itemid;
3193 $result = DBA::insert('thread', $item);
3195 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3199 private static function updateThread($itemid, $setmention = false)
3201 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3202 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3203 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3204 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3206 $item = self::selectFirst($fields, $condition);
3207 if (!DBA::isResult($item)) {
3212 $item["mention"] = 1;
3219 foreach ($item as $field => $data) {
3220 if (!in_array($field, ["guid"])) {
3221 $fields[$field] = $data;
3225 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3227 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3230 private static function deleteThread($itemid, $itemuri = "")
3232 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3233 if (!DBA::isResult($item)) {
3234 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3238 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3240 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3242 if ($itemuri != "") {
3243 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3244 if (!self::exists($condition)) {
3245 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3246 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);
3251 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null)
3253 $local_user = local_user();
3254 $remote_user = remote_user();
3257 * Construct permissions
3259 * default permissions - anonymous user
3261 $sql = " AND NOT `item`.`private`";
3263 // Profile owner - everything is visible
3264 if ($local_user && ($local_user == $owner_id)) {
3266 } elseif ($remote_user) {
3268 * Authenticated visitor. Unless pre-verified,
3269 * check that the contact belongs to this $owner_id
3270 * and load the groups the visitor belongs to.
3271 * If pre-verified, the caller is expected to have already
3272 * done this and passed the groups into this function.
3274 $set = PermissionSet::get($owner_id, $remote_user, $groups);
3277 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3282 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";