4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\Lock;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\PermissionSet;
21 use Friendica\Model\ItemURI;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use Text_LanguageDetect;
29 require_once 'boot.php';
30 require_once 'include/items.php';
31 require_once 'include/text.php';
33 class Item extends BaseObject
35 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
42 const PT_DOCUMENT = 19;
44 const PT_PERSONAL_NOTE = 128;
46 // Field list that is used to display the items
47 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
48 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
49 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
50 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
51 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
52 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
53 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
54 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
55 'writable', 'self', 'cid', 'alias',
56 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
57 'event-summary', 'event-desc', 'event-location', 'event-type',
58 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
60 // Field list that is used to deliver items via the protocols
61 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
62 'created', 'edited', 'verb', 'object-type', 'object', 'target',
63 'private', 'title', 'body', 'location', 'coord', 'app',
64 'attach', 'tag', 'deleted', 'extid', 'post-type',
65 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
66 'author-id', 'author-link', 'owner-link', 'contact-uid',
67 'signed_text', 'signature', 'signer', 'network'];
69 // Field list for "item-content" table that is mixed with the item table
70 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
71 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
72 'object-type', 'object', 'target-type', 'target', 'plink'];
74 // Field list for "item-content" table that is not present in the "item" table
75 const CONTENT_FIELDLIST = ['language'];
77 // Field list for additional delivery data
78 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
80 // All fields in the item table
81 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
82 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
83 'uri-hash', 'created', 'edited', 'commented', 'received', 'changed', 'verb',
84 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
85 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
86 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
87 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
88 'title', 'content-warning', 'body', 'location', 'coord', 'app',
89 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
90 'author-id', 'author-link', 'author-name', 'author-avatar',
91 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
93 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
94 // The item-activity table only stores the index and needs this array to know the matching activity.
95 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
97 private static $legacy_mode = null;
99 public static function isLegacyMode()
101 if (is_null(self::$legacy_mode)) {
102 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
105 return self::$legacy_mode;
109 * @brief returns an activity index from an activity string
111 * @param string $activity activity string
112 * @return integer Activity index
114 public static function activityToIndex($activity)
116 $index = array_search($activity, self::ACTIVITIES);
118 if (is_bool($index)) {
126 * @brief returns an activity string from an activity index
128 * @param integer $index activity index
129 * @return string Activity string
131 private static function indexToActivity($index)
133 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
137 return self::ACTIVITIES[$index];
141 * @brief Fetch a single item row
143 * @param mixed $stmt statement object
144 * @return array current row
146 public static function fetch($stmt)
148 $row = DBA::fetch($stmt);
154 // ---------------------- Transform item structure data ----------------------
156 // We prefer the data from the user's contact over the public one
157 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
158 ($row['author-link'] == $row['contact-link'])) {
159 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
160 $row['author-avatar'] = $row['contact-avatar'];
162 if (isset($row['author-name']) && !empty($row['contact-name'])) {
163 $row['author-name'] = $row['contact-name'];
167 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
168 ($row['owner-link'] == $row['contact-link'])) {
169 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
170 $row['owner-avatar'] = $row['contact-avatar'];
172 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
173 $row['owner-name'] = $row['contact-name'];
177 // We can always comment on posts from these networks
178 if (array_key_exists('writable', $row) &&
179 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
180 $row['writable'] = true;
183 // ---------------------- Transform item content data ----------------------
185 // Fetch data from the item-content table whenever there is content there
186 if (self::isLegacyMode()) {
187 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
188 foreach ($legacy_fields as $field) {
189 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
190 $row[$field] = $row['internal-item-' . $field];
192 unset($row['internal-item-' . $field]);
196 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
197 $row['verb'] = self::indexToActivity($row['internal-activity']);
198 if (array_key_exists('title', $row)) {
201 if (array_key_exists('body', $row)) {
202 $row['body'] = $row['verb'];
204 if (array_key_exists('object', $row)) {
207 if (array_key_exists('object-type', $row)) {
208 $row['object-type'] = ACTIVITY_OBJ_NOTE;
210 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
211 // Posts don't have an object or target - but having tags or files.
212 // We safe some performance by building tag and file strings only here.
213 // We remove object and target since they aren't used for this type.
214 if (array_key_exists('object', $row)) {
217 if (array_key_exists('target', $row)) {
222 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
223 // Build the tag string out of the term entries
224 if (array_key_exists('tag', $row) && empty($row['tag'])) {
225 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
228 // Build the file string out of the term entries
229 if (array_key_exists('file', $row) && empty($row['file'])) {
230 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
234 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
235 $row['signed_text'] = $row['interaction'];
238 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
239 $row['ignored'] = $row['internal-user-ignored'];
242 // Remove internal fields
243 unset($row['internal-activity']);
244 unset($row['internal-network']);
245 unset($row['internal-iid']);
246 unset($row['internal-iaid']);
247 unset($row['internal-icid']);
248 unset($row['internal-user-ignored']);
249 unset($row['interaction']);
255 * @brief Fills an array with data from an item query
257 * @param object $stmt statement object
258 * @return array Data array
260 public static function inArray($stmt, $do_close = true) {
261 if (is_bool($stmt)) {
266 while ($row = self::fetch($stmt)) {
276 * @brief Check if item data exists
278 * @param array $condition array of fields for condition
280 * @return boolean Are there rows for that condition?
282 public static function exists($condition) {
283 $stmt = self::select(['id'], $condition, ['limit' => 1]);
285 if (is_bool($stmt)) {
288 $retval = (DBA::numRows($stmt) > 0);
297 * Retrieve a single record from the item table for a given user and returns it in an associative array
299 * @brief Retrieve a single record from a table
300 * @param integer $uid User ID
301 * @param array $fields
302 * @param array $condition
303 * @param array $params
307 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
309 $params['uid'] = $uid;
311 if (empty($selected)) {
312 $selected = Item::DISPLAY_FIELDLIST;
315 return self::selectFirst($selected, $condition, $params);
319 * @brief Select rows from the item table for a given user
321 * @param integer $uid User ID
322 * @param array $selected Array of selected fields, empty for all
323 * @param array $condition Array of fields for condition
324 * @param array $params Array of several parameters
326 * @return boolean|object
328 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
330 $params['uid'] = $uid;
332 if (empty($selected)) {
333 $selected = Item::DISPLAY_FIELDLIST;
336 return self::select($selected, $condition, $params);
340 * Retrieve a single record from the item table and returns it in an associative array
342 * @brief Retrieve a single record from a table
343 * @param array $fields
344 * @param array $condition
345 * @param array $params
349 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
351 $params['limit'] = 1;
353 $result = self::select($fields, $condition, $params);
355 if (is_bool($result)) {
358 $row = self::fetch($result);
365 * @brief Select rows from the item table
367 * @param array $selected Array of selected fields, empty for all
368 * @param array $condition Array of fields for condition
369 * @param array $params Array of several parameters
371 * @return boolean|object
373 public static function select(array $selected = [], array $condition = [], $params = [])
378 if (isset($params['uid'])) {
379 $uid = $params['uid'];
383 $fields = self::fieldlist($usermode);
385 $select_fields = self::constructSelectFields($fields, $selected);
387 $condition_string = DBA::buildCondition($condition);
389 $condition_string = self::addTablesToFields($condition_string, $fields);
392 $condition_string = $condition_string . ' AND ' . self::condition(false);
395 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
397 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
399 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
401 return DBA::p($sql, $condition);
405 * @brief Select rows from the starting post in the item table
407 * @param integer $uid User ID
408 * @param array $fields Array of selected fields, empty for all
409 * @param array $condition Array of fields for condition
410 * @param array $params Array of several parameters
412 * @return boolean|object
414 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
416 $params['uid'] = $uid;
418 if (empty($selected)) {
419 $selected = Item::DISPLAY_FIELDLIST;
422 return self::selectThread($selected, $condition, $params);
426 * Retrieve a single record from the starting post in the item table and returns it in an associative array
428 * @brief Retrieve a single record from a table
429 * @param integer $uid User ID
430 * @param array $selected
431 * @param array $condition
432 * @param array $params
436 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
438 $params['uid'] = $uid;
440 if (empty($selected)) {
441 $selected = Item::DISPLAY_FIELDLIST;
444 return self::selectFirstThread($selected, $condition, $params);
448 * Retrieve a single record from the starting post in the item table and returns it in an associative array
450 * @brief Retrieve a single record from a table
451 * @param array $fields
452 * @param array $condition
453 * @param array $params
457 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
459 $params['limit'] = 1;
460 $result = self::selectThread($fields, $condition, $params);
462 if (is_bool($result)) {
465 $row = self::fetch($result);
472 * @brief Select rows from the starting post in the item table
474 * @param array $selected Array of selected fields, empty for all
475 * @param array $condition Array of fields for condition
476 * @param array $params Array of several parameters
478 * @return boolean|object
480 public static function selectThread(array $selected = [], array $condition = [], $params = [])
485 if (isset($params['uid'])) {
486 $uid = $params['uid'];
490 $fields = self::fieldlist($usermode);
492 $fields['thread'] = ['mention', 'ignored', 'iid'];
494 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
495 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
496 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
497 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
499 $select_fields = self::constructSelectFields($fields, $selected);
501 $condition_string = DBA::buildCondition($condition);
503 $condition_string = self::addTablesToFields($condition_string, $threadfields);
504 $condition_string = self::addTablesToFields($condition_string, $fields);
507 $condition_string = $condition_string . ' AND ' . self::condition(true);
510 $param_string = DBA::buildParameter($params);
511 $param_string = self::addTablesToFields($param_string, $threadfields);
512 $param_string = self::addTablesToFields($param_string, $fields);
514 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
516 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
518 return DBA::p($sql, $condition);
522 * @brief Returns a list of fields that are associated with the item table
524 * @return array field list
526 private static function fieldlist($usermode)
530 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
531 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
532 'created', 'edited', 'commented', 'received', 'changed', 'psid', 'uri-hash',
533 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
534 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
535 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
536 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
537 'network' => 'internal-network', 'icid' => 'internal-icid',
538 'iaid' => 'internal-iaid'];
541 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
544 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
546 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
548 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
550 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
552 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
553 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
555 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
556 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
558 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
559 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
560 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
562 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
564 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
566 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
567 'start' => 'event-start','finish' => 'event-finish',
568 'summary' => 'event-summary','desc' => 'event-desc',
569 'location' => 'event-location', 'type' => 'event-type',
570 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
571 'ignore' => 'event-ignore', 'id' => 'event-id'];
573 $fields['sign'] = ['signed_text', 'signature', 'signer'];
575 $fields['diaspora-interaction'] = ['interaction'];
581 * @brief Returns SQL condition for the "select" functions
583 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
585 * @return string SQL condition
587 private static function condition($thread_mode)
590 $master_table = "`thread`";
592 $master_table = "`item`";
594 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
595 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
596 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
597 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
598 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
599 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
600 GRAVITY_PARENT, GRAVITY_PARENT);
604 * @brief Returns all needed "JOIN" commands for the "select" functions
606 * @param integer $uid User ID
607 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
608 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
610 * @return string The SQL joins for the "select" functions
612 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
615 $master_table = "`thread`";
616 $master_table_key = "`thread`.`iid`";
617 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
619 $master_table = "`item`";
620 $master_table_key = "`item`.`id`";
625 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
626 AND NOT `contact`.`blocked`
627 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
628 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
629 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
630 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
631 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
632 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
633 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
634 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
636 if (strpos($sql_commands, "`contact`.") !== false) {
637 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
639 if (strpos($sql_commands, "`author`.") !== false) {
640 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
642 if (strpos($sql_commands, "`owner`.") !== false) {
643 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
647 if (strpos($sql_commands, "`group_member`.") !== false) {
648 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
651 if (strpos($sql_commands, "`user`.") !== false) {
652 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
655 if (strpos($sql_commands, "`event`.") !== false) {
656 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
659 if (strpos($sql_commands, "`sign`.") !== false) {
660 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
663 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
664 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
667 if (strpos($sql_commands, "`item-activity`.") !== false) {
668 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
671 if (strpos($sql_commands, "`item-content`.") !== false) {
672 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
675 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
676 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
679 if (strpos($sql_commands, "`permissionset`.") !== false) {
680 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
683 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
684 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
687 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
688 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
695 * @brief Add the field list for the "select" functions
697 * @param array $fields The field definition array
698 * @param array $selected The array with the selected fields from the "select" functions
700 * @return string The field list
702 private static function constructSelectFields($fields, $selected)
704 if (!empty($selected)) {
705 $selected[] = 'internal-iid';
706 $selected[] = 'internal-iaid';
707 $selected[] = 'internal-icid';
708 $selected[] = 'internal-network';
711 if (in_array('verb', $selected)) {
712 $selected[] = 'internal-activity';
715 if (in_array('ignored', $selected)) {
716 $selected[] = 'internal-user-ignored';
719 if (in_array('signed_text', $selected)) {
720 $selected[] = 'interaction';
724 foreach ($fields as $table => $table_fields) {
725 foreach ($table_fields as $field => $select) {
726 if (empty($selected) || in_array($select, $selected)) {
727 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
728 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
729 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
731 if (is_int($field)) {
732 $selection[] = "`" . $table . "`.`" . $select . "`";
734 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
739 return implode(", ", $selection);
743 * @brief add table definition to fields in an SQL query
745 * @param string $query SQL query
746 * @param array $fields The field definition array
748 * @return string the changed SQL query
750 private static function addTablesToFields($query, $fields)
752 foreach ($fields as $table => $table_fields) {
753 foreach ($table_fields as $alias => $field) {
754 if (is_int($alias)) {
755 $replace_field = $field;
757 $replace_field = $alias;
760 $search = "/([^\.])`" . $field . "`/i";
761 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
762 $query = preg_replace($search, $replace, $query);
769 * @brief Generate a server unique item hash for linking between the item tables
771 * @param string $uri Item URI
772 * @param date $created Item creation date
774 * @return string the item hash
776 private static function itemHash($uri, $created)
778 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
782 * @brief Update existing item entries
784 * @param array $fields The fields that are to be changed
785 * @param array $condition The condition for finding the item entries
787 * In the future we may have to change permissions as well.
788 * Then we had to add the user id as third parameter.
790 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
792 * @return integer|boolean number of affected rows - or "false" if there was an error
794 public static function update(array $fields, array $condition)
796 if (empty($condition) || empty($fields)) {
800 // To ensure the data integrity we do it in an transaction
803 // We cannot simply expand the condition to check for origin entries
804 // The condition needn't to be a simple array but could be a complex condition.
805 // And we have to execute this query before the update to ensure to fetch the same data.
806 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
808 $content_fields = [];
809 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
810 if (isset($fields[$field])) {
811 $content_fields[$field] = $fields[$field];
812 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
813 unset($fields[$field]);
815 $fields[$field] = null;
820 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
821 foreach ($clear_fields as $field) {
822 if (array_key_exists($field, $fields)) {
823 $fields[$field] = null;
827 if (array_key_exists('tag', $fields)) {
828 $tags = $fields['tag'];
829 $fields['tag'] = null;
834 if (array_key_exists('file', $fields)) {
835 $files = $fields['file'];
836 $fields['file'] = null;
841 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
842 'inform' => defaults($fields, 'inform', '')];
844 $fields['postopts'] = null;
845 $fields['inform'] = null;
847 if (!empty($fields)) {
848 $success = DBA::update('item', $fields, $condition);
857 // When there is no content for the "old" item table, this will count the fetched items
858 $rows = DBA::affectedRows();
860 while ($item = DBA::fetch($items)) {
862 // This part here can safely be removed when the legacy fields in the item had been removed
863 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
865 // Fetch the uri-hash from an existing item entry if there is one
866 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
867 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
868 if (DBA::isResult($existing)) {
869 $item['uri-hash'] = $existing['uri-hash'];
871 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
874 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
875 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
876 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
879 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
880 if (!empty($item['iaid'])) {
881 $update_condition = ['id' => $item['iaid']];
883 $update_condition = ['uri-hash' => $item['uri-hash']];
885 self::updateActivity($content_fields, $update_condition);
887 if (empty($item['iaid'])) {
888 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
889 if (DBA::isResult($item_activity)) {
890 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
891 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
892 if (self::isLegacyMode()) {
893 $item_fields[$field] = null;
895 unset($item_fields[$field]);
898 DBA::update('item', $item_fields, ['id' => $item['id']]);
900 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
901 DBA::delete('item-content', ['id' => $item['icid']]);
904 } elseif (!empty($item['icid'])) {
905 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
907 if (!DBA::exists('item', ['icid' => $item['icid']])) {
908 DBA::delete('item-content', ['id' => $item['icid']]);
912 if (!empty($item['icid'])) {
913 $update_condition = ['id' => $item['icid']];
915 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
917 self::updateContent($content_fields, $update_condition);
919 if (empty($item['icid'])) {
920 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
921 if (DBA::isResult($item_content)) {
922 $item_fields = ['icid' => $item_content['id']];
923 // Clear all fields in the item table that have a content in the item-content table
924 foreach ($item_content as $field => $content) {
925 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
926 if (self::isLegacyMode()) {
927 $item_fields[$field] = null;
929 unset($item_fields[$field]);
933 DBA::update('item', $item_fields, ['id' => $item['id']]);
939 Term::insertFromTagFieldByItemId($item['id'], $tags);
940 if (!empty($item['tag'])) {
941 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
945 if (!empty($files)) {
946 Term::insertFromFileFieldByItemId($item['id'], $files);
947 if (!empty($item['file'])) {
948 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
952 self::updateDeliveryData($item['id'], $delivery_data);
954 self::updateThread($item['id']);
956 // We only need to notfiy others when it is an original entry from us.
957 // Only call the notifier when the item has some content relevant change.
958 if ($item['origin'] && in_array('edited', array_keys($fields))) {
959 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
969 * @brief Delete an item and notify others about it - if it was ours
971 * @param array $condition The condition for finding the item entries
972 * @param integer $priority Priority for the notification
974 public static function delete($condition, $priority = PRIORITY_HIGH)
976 $items = self::select(['id'], $condition);
977 while ($item = self::fetch($items)) {
978 self::deleteById($item['id'], $priority);
984 * @brief Delete an item for an user and notify others about it - if it was ours
986 * @param array $condition The condition for finding the item entries
987 * @param integer $uid User who wants to delete this item
989 public static function deleteForUser($condition, $uid)
995 $items = self::select(['id', 'uid'], $condition);
996 while ($item = self::fetch($items)) {
997 // "Deleting" global items just means hiding them
998 if ($item['uid'] == 0) {
999 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1000 } elseif ($item['uid'] == $uid) {
1001 self::deleteById($item['id'], PRIORITY_HIGH);
1003 logger('Wrong ownership. Not deleting item ' . $item['id']);
1010 * @brief Delete an item and notify others about it - if it was ours
1012 * @param integer $item_id Item ID that should be delete
1013 * @param integer $priority Priority for the notification
1015 * @return boolean success
1017 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
1019 // locate item to be deleted
1020 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1021 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1022 'verb', 'object-type', 'object', 'target', 'contact-id',
1023 'icid', 'iaid', 'psid'];
1024 $item = self::selectFirst($fields, ['id' => $item_id]);
1025 if (!DBA::isResult($item)) {
1026 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
1030 if ($item['deleted']) {
1031 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
1035 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1036 if (!DBA::isResult($parent)) {
1037 $parent = ['origin' => false];
1040 // clean up categories and tags so they don't end up as orphans
1043 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1045 foreach ($matches as $mtch) {
1046 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1052 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1054 foreach ($matches as $mtch) {
1055 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1060 * If item is a link to a photo resource, nuke all the associated photos
1061 * (visitors will not have photo resources)
1062 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1063 * generate a resource-id and therefore aren't intimately linked to the item.
1065 if (strlen($item['resource-id'])) {
1066 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1069 // If item is a link to an event, delete the event.
1070 if (intval($item['event-id'])) {
1071 Event::delete($item['event-id']);
1074 // If item has attachments, drop them
1075 foreach (explode(", ", $item['attach']) as $attach) {
1076 preg_match("|attach/(\d+)|", $attach, $matches);
1077 if (is_array($matches) && count($matches) > 1) {
1078 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1082 // Delete tags that had been attached to other items
1083 self::deleteTagsFromItem($item);
1085 // Set the item to "deleted"
1086 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1087 DBA::update('item', $item_fields, ['id' => $item['id']]);
1089 Term::insertFromTagFieldByItemId($item['id'], '');
1090 Term::insertFromFileFieldByItemId($item['id'], '');
1091 self::deleteThread($item['id'], $item['parent-uri']);
1093 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1094 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1097 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1099 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1101 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1102 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1104 // When the permission set will be used in photo and events as well,
1105 // this query here needs to be extended.
1106 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1107 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1110 // If it's the parent of a comment thread, kill all the kids
1111 if ($item['id'] == $item['parent']) {
1112 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1115 // Is it our comment and/or our thread?
1116 if ($item['origin'] || $parent['origin']) {
1118 // When we delete the original post we will delete all existing copies on the server as well
1119 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1121 // send the notification upstream/downstream
1122 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1123 } elseif ($item['uid'] != 0) {
1125 // When we delete just our local user copy of an item, we have to set a marker to hide it
1126 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1127 if (DBA::isResult($global_item)) {
1128 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1132 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1137 private static function deleteTagsFromItem($item)
1139 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1143 $xo = XML::parseString($item["object"], false);
1144 $xt = XML::parseString($item["target"], false);
1146 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1150 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1151 if (!DBA::isResult($i)) {
1155 // For tags, the owner cannot remove the tag on the author's copy of the post.
1156 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1157 $author_copy = $item["origin"];
1159 if (($owner_remove && $author_copy) || !$owner_remove) {
1163 $tags = explode(',', $i["tag"]);
1166 foreach ($tags as $tag) {
1167 if (trim($tag) !== trim($xo->body)) {
1168 $newtags[] = trim($tag);
1172 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1175 private static function guid($item, $notify)
1177 if (!empty($item['guid'])) {
1178 return notags(trim($item['guid']));
1182 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1183 // We add the hash of our own host because our host is the original creator of the post.
1184 $prefix_host = get_app()->getHostName();
1188 // We are only storing the post so we create a GUID from the original hostname.
1189 if (!empty($item['author-link'])) {
1190 $parsed = parse_url($item['author-link']);
1191 if (!empty($parsed['host'])) {
1192 $prefix_host = $parsed['host'];
1196 if (empty($prefix_host) && !empty($item['plink'])) {
1197 $parsed = parse_url($item['plink']);
1198 if (!empty($parsed['host'])) {
1199 $prefix_host = $parsed['host'];
1203 if (empty($prefix_host) && !empty($item['uri'])) {
1204 $parsed = parse_url($item['uri']);
1205 if (!empty($parsed['host'])) {
1206 $prefix_host = $parsed['host'];
1210 // Is it in the format data@host.tld? - Used for mail contacts
1211 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1212 $mailparts = explode('@', $item['author-link']);
1213 $prefix_host = array_pop($mailparts);
1217 if (!empty($item['plink'])) {
1218 $guid = self::guidFromUri($item['plink'], $prefix_host);
1219 } elseif (!empty($item['uri'])) {
1220 $guid = self::guidFromUri($item['uri'], $prefix_host);
1222 $guid = System::createUUID(hash('crc32', $prefix_host));
1228 private static function contactId($item)
1230 $contact_id = (int)$item["contact-id"];
1232 if (!empty($contact_id)) {
1235 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1237 * First we are looking for a suitable contact that matches with the author of the post
1238 * This is done only for comments
1240 if ($item['parent-uri'] != $item['uri']) {
1241 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1244 // If not present then maybe the owner was found
1245 if ($contact_id == 0) {
1246 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1249 // Still missing? Then use the "self" contact of the current user
1250 if ($contact_id == 0) {
1251 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1252 if (DBA::isResult($self)) {
1253 $contact_id = $self["id"];
1256 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1261 // This function will finally cover most of the preparation functionality in mod/item.php
1262 public static function prepare(&$item)
1264 $data = BBCode::getAttachmentData($item['body']);
1265 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1266 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1267 $posttype = Item::PT_PAGE;
1268 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1272 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1276 // If it is a posting where users should get notifications, then define it as wall posting
1279 $item['origin'] = 1;
1280 $item['network'] = Protocol::DFRN;
1281 $item['protocol'] = Conversation::PARCEL_DFRN;
1283 if (is_int($notify)) {
1284 $priority = $notify;
1286 $priority = PRIORITY_HIGH;
1289 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1292 $item['guid'] = self::guid($item, $notify);
1293 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1296 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1298 // Store conversation data
1299 $item = Conversation::insert($item);
1302 * If a Diaspora signature structure was passed in, pull it out of the
1303 * item array and set it aside for later storage.
1307 if (isset($item['dsprsig'])) {
1308 $encoded_signature = $item['dsprsig'];
1309 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1310 unset($item['dsprsig']);
1313 $diaspora_signed_text = '';
1314 if (isset($item['diaspora_signed_text'])) {
1315 $diaspora_signed_text = $item['diaspora_signed_text'];
1316 unset($item['diaspora_signed_text']);
1319 // Converting the plink
1320 /// @TODO Check if this is really still needed
1321 if ($item['network'] == Protocol::OSTATUS) {
1322 if (isset($item['plink'])) {
1323 $item['plink'] = OStatus::convertHref($item['plink']);
1324 } elseif (isset($item['uri'])) {
1325 $item['plink'] = OStatus::convertHref($item['uri']);
1329 if (!empty($item['thr-parent'])) {
1330 $item['parent-uri'] = $item['thr-parent'];
1333 if (isset($item['gravity'])) {
1334 $item['gravity'] = intval($item['gravity']);
1335 } elseif ($item['parent-uri'] === $item['uri']) {
1336 $item['gravity'] = GRAVITY_PARENT;
1337 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1338 $item['gravity'] = GRAVITY_COMMENT;
1340 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1341 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1344 $uid = intval($item['uid']);
1346 // check for create date and expire time
1347 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1349 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1350 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1351 $expire_interval = $user['expire'];
1354 if (($expire_interval > 0) && !empty($item['created'])) {
1355 $expire_date = time() - ($expire_interval * 86400);
1356 $created_date = strtotime($item['created']);
1357 if ($created_date < $expire_date) {
1358 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1364 * Do we already have this item?
1365 * We have to check several networks since Friendica posts could be repeated
1366 * via OStatus (maybe Diasporsa as well)
1368 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1369 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1370 trim($item['uri']), $item['uid'],
1371 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1372 $existing = self::selectFirst(['id', 'network'], $condition);
1373 if (DBA::isResult($existing)) {
1374 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1376 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1379 return $existing["id"];
1383 // Ensure to always have the same creation date.
1384 $existing = self::selectfirst(['created', 'uri-hash'], ['uri' => $item['uri']]);
1385 if (DBA::isResult($existing)) {
1386 $item['created'] = $existing['created'];
1387 $item['uri-hash'] = $existing['uri-hash'];
1390 $item['wall'] = intval(defaults($item, 'wall', 0));
1391 $item['extid'] = trim(defaults($item, 'extid', ''));
1392 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1393 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1394 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1395 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1396 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1397 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1398 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1399 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1400 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1401 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1402 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1403 $item['title'] = trim(defaults($item, 'title', ''));
1404 $item['location'] = trim(defaults($item, 'location', ''));
1405 $item['coord'] = trim(defaults($item, 'coord', ''));
1406 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1407 $item['deleted'] = 0;
1408 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1409 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1410 $item['verb'] = trim(defaults($item, 'verb', ''));
1411 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1412 $item['object'] = trim(defaults($item, 'object', ''));
1413 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1414 $item['target'] = trim(defaults($item, 'target', ''));
1415 $item['plink'] = trim(defaults($item, 'plink', ''));
1416 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1417 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1418 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1419 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1420 $item['private'] = intval(defaults($item, 'private', 0));
1421 $item['body'] = trim(defaults($item, 'body', ''));
1422 $item['tag'] = trim(defaults($item, 'tag', ''));
1423 $item['attach'] = trim(defaults($item, 'attach', ''));
1424 $item['app'] = trim(defaults($item, 'app', ''));
1425 $item['origin'] = intval(defaults($item, 'origin', 0));
1426 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1427 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1428 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1429 $item['inform'] = trim(defaults($item, 'inform', ''));
1430 $item['file'] = trim(defaults($item, 'file', ''));
1432 // Unique identifier to be linked against item-activities and item-content
1433 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1435 // When there is no content then we don't post it
1436 if ($item['body'].$item['title'] == '') {
1437 logger('No body, no title.');
1441 self::addLanguageToItemArray($item);
1443 // Items cannot be stored before they happen ...
1444 if ($item['created'] > DateTimeFormat::utcNow()) {
1445 $item['created'] = DateTimeFormat::utcNow();
1448 // We haven't invented time travel by now.
1449 if ($item['edited'] > DateTimeFormat::utcNow()) {
1450 $item['edited'] = DateTimeFormat::utcNow();
1453 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1455 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1456 $item["contact-id"] = self::contactId($item);
1458 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1459 'photo' => $item['author-avatar'], 'network' => $item['network']];
1461 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1463 if (Contact::isBlocked($item["author-id"])) {
1464 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1468 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1469 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1471 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1473 if (Contact::isBlocked($item["owner-id"])) {
1474 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1478 if ($item['network'] == Protocol::PHANTOM) {
1479 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1481 $item['network'] = Protocol::DFRN;
1482 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1485 // Checking if there is already an item with the same guid
1486 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1487 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1488 if (self::exists($condition)) {
1489 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1493 // Check for hashtags in the body and repair or add hashtag links
1494 self::setHashtags($item);
1496 $item['thr-parent'] = $item['parent-uri'];
1504 if ($item['parent-uri'] === $item['uri']) {
1506 $parent_deleted = 0;
1507 $allow_cid = $item['allow_cid'];
1508 $allow_gid = $item['allow_gid'];
1509 $deny_cid = $item['deny_cid'];
1510 $deny_gid = $item['deny_gid'];
1511 $notify_type = 'wall-new';
1513 // find the parent and snarf the item id and ACLs
1514 // and anything else we need to inherit
1516 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1517 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1518 'wall', 'private', 'forum_mode', 'origin'];
1519 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1520 $params = ['order' => ['id' => false]];
1521 $parent = self::selectFirst($fields, $condition, $params);
1523 if (DBA::isResult($parent)) {
1524 // is the new message multi-level threaded?
1525 // even though we don't support it now, preserve the info
1526 // and re-attach to the conversation parent.
1528 if ($parent['uri'] != $parent['parent-uri']) {
1529 $item['parent-uri'] = $parent['parent-uri'];
1531 $condition = ['uri' => $item['parent-uri'],
1532 'parent-uri' => $item['parent-uri'],
1533 'uid' => $item['uid']];
1534 $params = ['order' => ['id' => false]];
1535 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1537 if (DBA::isResult($toplevel_parent)) {
1538 $parent = $toplevel_parent;
1542 $parent_id = $parent['id'];
1543 $parent_deleted = $parent['deleted'];
1544 $allow_cid = $parent['allow_cid'];
1545 $allow_gid = $parent['allow_gid'];
1546 $deny_cid = $parent['deny_cid'];
1547 $deny_gid = $parent['deny_gid'];
1548 $item['wall'] = $parent['wall'];
1549 $notify_type = 'comment-new';
1552 * If the parent is private, force privacy for the entire conversation
1553 * This differs from the above settings as it subtly allows comments from
1554 * email correspondents to be private even if the overall thread is not.
1556 if ($parent['private']) {
1557 $item['private'] = $parent['private'];
1561 * Edge case. We host a public forum that was originally posted to privately.
1562 * The original author commented, but as this is a comment, the permissions
1563 * weren't fixed up so it will still show the comment as private unless we fix it here.
1565 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1566 $item['private'] = 0;
1569 // If its a post from myself then tag the thread as "mention"
1570 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1571 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1572 if (DBA::isResult($user)) {
1573 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1574 $self_id = Contact::getIdForURL($self, 0, true);
1575 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1576 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1577 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1578 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1583 * Allow one to see reply tweets from status.net even when
1584 * we don't have or can't see the original post.
1586 if ($force_parent) {
1587 logger('$force_parent=true, reply converted to top-level post.');
1589 $item['parent-uri'] = $item['uri'];
1590 $item['gravity'] = GRAVITY_PARENT;
1592 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1596 $parent_deleted = 0;
1600 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1601 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1603 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1604 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1605 if (self::exists($condition)) {
1606 logger('duplicated item with the same uri found. '.print_r($item,true));
1610 // On Friendica and Diaspora the GUID is unique
1611 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1612 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1613 if (self::exists($condition)) {
1614 logger('duplicated item with the same guid found. '.print_r($item,true));
1618 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1619 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1620 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1621 if (self::exists($condition)) {
1622 logger('duplicated item with the same body found. '.print_r($item,true));
1627 // Is this item available in the global items (with uid=0)?
1628 if ($item["uid"] == 0) {
1629 $item["global"] = true;
1631 // Set the global flag on all items if this was a global item entry
1632 self::update(['global' => true], ['uri' => $item["uri"]]);
1634 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1638 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1641 $private = $item['private'];
1644 $item["allow_cid"] = $allow_cid;
1645 $item["allow_gid"] = $allow_gid;
1646 $item["deny_cid"] = $deny_cid;
1647 $item["deny_gid"] = $deny_gid;
1648 $item["private"] = $private;
1649 $item["deleted"] = $parent_deleted;
1651 // Fill the cache field
1652 put_item_in_cache($item);
1655 $item['edit'] = false;
1656 $item['parent'] = $parent_id;
1657 Addon::callHooks('post_local', $item);
1658 unset($item['edit']);
1659 unset($item['parent']);
1661 Addon::callHooks('post_remote', $item);
1664 // This array field is used to trigger some automatic reactions
1665 // It is mainly used in the "post_local" hook.
1666 unset($item['api_source']);
1668 if (x($item, 'cancel')) {
1669 logger('post cancelled by addon.');
1674 * Check for already added items.
1675 * There is a timing issue here that sometimes creates double postings.
1676 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1678 if ($item["uid"] == 0) {
1679 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1680 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1685 logger('' . print_r($item,true), LOGGER_DATA);
1687 if (array_key_exists('tag', $item)) {
1688 $tags = $item['tag'];
1689 unset($item['tag']);
1694 if (array_key_exists('file', $item)) {
1695 $files = $item['file'];
1696 unset($item['file']);
1701 // Creates or assigns the permission set
1702 $item['psid'] = PermissionSet::fetchIDForPost($item);
1704 // We are doing this outside of the transaction to avoid timing problems
1705 if (!self::insertActivity($item)) {
1706 self::insertContent($item);
1709 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1710 'inform' => defaults($item, 'inform', '')];
1712 unset($item['postopts']);
1713 unset($item['inform']);
1715 // These fields aren't stored anymore in the item table, they are fetched upon request
1716 unset($item['author-link']);
1717 unset($item['author-name']);
1718 unset($item['author-avatar']);
1720 unset($item['owner-link']);
1721 unset($item['owner-name']);
1722 unset($item['owner-avatar']);
1725 $ret = DBA::insert('item', $item);
1727 // When the item was successfully stored we fetch the ID of the item.
1728 if (DBA::isResult($ret)) {
1729 $current_post = DBA::lastInsertId();
1731 // This can happen - for example - if there are locking timeouts.
1734 // Store the data into a spool file so that we can try again later.
1736 // At first we restore the Diaspora signature that we removed above.
1737 if (isset($encoded_signature)) {
1738 $item['dsprsig'] = $encoded_signature;
1741 // Now we store the data in the spool directory
1742 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1743 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1745 $spoolpath = get_spoolpath();
1746 if ($spoolpath != "") {
1747 $spool = $spoolpath.'/'.$file;
1749 // Ensure to have the removed data from above again in the item array
1750 $item = array_merge($item, $delivery_data);
1752 file_put_contents($spool, json_encode($item));
1753 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1758 if ($current_post == 0) {
1759 // This is one of these error messages that never should occur.
1760 logger("couldn't find created item - we better quit now.");
1765 // How much entries have we created?
1766 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1767 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1770 // There are duplicates. We delete our just created entry.
1771 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1773 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1774 DBA::delete('item', ['id' => $current_post]);
1777 } elseif ($entries == 0) {
1778 // This really should never happen since we quit earlier if there were problems.
1779 logger("Something is terribly wrong. We haven't found our created entry.");
1784 logger('created item '.$current_post);
1785 self::updateContact($item);
1787 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1788 $parent_id = $current_post;
1792 self::update(['parent' => $parent_id], ['id' => $current_post]);
1794 $item['id'] = $current_post;
1795 $item['parent'] = $parent_id;
1797 // update the commented timestamp on the parent
1798 // Only update "commented" if it is really a comment
1799 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1800 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1802 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1807 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1808 * We can check for this condition when we decode and encode the stuff again.
1810 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1811 $dsprsig->signature = base64_decode($dsprsig->signature);
1812 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1815 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1816 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1818 // The other fields are used by very old Friendica servers, so we currently store them differently
1819 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1820 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1824 if (!empty($diaspora_signed_text)) {
1825 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1828 $deleted = self::tagDeliver($item['uid'], $current_post);
1831 * current post can be deleted if is for a community page and no mention are
1834 if (!$deleted && !$dontcache) {
1835 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1836 if (DBA::isResult($posted_item)) {
1838 Addon::callHooks('post_local_end', $posted_item);
1840 Addon::callHooks('post_remote_end', $posted_item);
1843 logger('new item not found in DB, id ' . $current_post);
1847 if ($item['parent-uri'] === $item['uri']) {
1848 self::addThread($current_post);
1850 self::updateThread($parent_id);
1853 $delivery_data['iid'] = $current_post;
1855 self::insertDeliveryData($delivery_data);
1860 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1861 * This is not perfect - but a workable solution until we found the reason for the problem.
1863 if (!empty($tags)) {
1864 Term::insertFromTagFieldByItemId($current_post, $tags);
1867 if (!empty($files)) {
1868 Term::insertFromFileFieldByItemId($current_post, $files);
1871 if ($item['parent-uri'] === $item['uri']) {
1872 self::addShadow($current_post);
1874 self::addShadowPost($current_post);
1877 check_user_notification($current_post);
1880 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1881 } elseif (!empty($parent) && $parent['origin']) {
1882 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1885 return $current_post;
1889 * @brief Insert a new item delivery data entry
1891 * @param array $item The item fields that are to be inserted
1893 private static function insertDeliveryData($delivery_data)
1895 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1899 DBA::insert('item-delivery-data', $delivery_data);
1903 * @brief Update an existing item delivery data entry
1905 * @param integer $id The item id that is to be updated
1906 * @param array $item The item fields that are to be inserted
1908 private static function updateDeliveryData($id, $delivery_data)
1910 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1914 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1918 * @brief Insert a new item content entry
1920 * @param array $item The item fields that are to be inserted
1922 private static function insertActivity(&$item)
1924 $activity_index = self::activityToIndex($item['verb']);
1926 if ($activity_index < 0) {
1930 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1931 'uri-hash' => $item['uri-hash'], 'uri-id' => $item['uri-id']];
1933 // We just remove everything that is content
1934 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1935 unset($item[$field]);
1938 // To avoid timing problems, we are using locks.
1939 $locked = Lock::acquire('item_insert_activity');
1941 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1944 // Do we already have this content?
1945 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1946 if (DBA::isResult($item_activity)) {
1947 $item['iaid'] = $item_activity['id'];
1948 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1949 } elseif (DBA::insert('item-activity', $fields)) {
1950 $item['iaid'] = DBA::lastInsertId();
1951 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1953 // This shouldn't happen.
1954 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1955 Lock::release('item_insert_activity');
1959 Lock::release('item_insert_activity');
1965 * @brief Insert a new item content entry
1967 * @param array $item The item fields that are to be inserted
1969 private static function insertContent(&$item)
1971 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash'],
1972 'uri-id' => $item['uri-id']];
1974 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1975 if (isset($item[$field])) {
1976 $fields[$field] = $item[$field];
1977 unset($item[$field]);
1981 // To avoid timing problems, we are using locks.
1982 $locked = Lock::acquire('item_insert_content');
1984 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1987 // Do we already have this content?
1988 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1989 if (DBA::isResult($item_content)) {
1990 $item['icid'] = $item_content['id'];
1991 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1992 } elseif (DBA::insert('item-content', $fields)) {
1993 $item['icid'] = DBA::lastInsertId();
1994 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1996 // This shouldn't happen.
1997 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2000 Lock::release('item_insert_content');
2005 * @brief Update existing item content entries
2007 * @param array $item The item fields that are to be changed
2008 * @param array $condition The condition for finding the item content entries
2010 private static function updateActivity($item, $condition)
2012 if (empty($item['verb'])) {
2015 $activity_index = self::activityToIndex($item['verb']);
2017 if ($activity_index < 0) {
2021 $fields = ['activity' => $activity_index];
2023 logger('Update activity for ' . json_encode($condition));
2025 DBA::update('item-activity', $fields, $condition, true);
2031 * @brief Update existing item content entries
2033 * @param array $item The item fields that are to be changed
2034 * @param array $condition The condition for finding the item content entries
2036 private static function updateContent($item, $condition)
2038 // We have to select only the fields from the "item-content" table
2040 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2041 if (isset($item[$field])) {
2042 $fields[$field] = $item[$field];
2046 if (empty($fields)) {
2047 // when there are no fields at all, just use the condition
2048 // This is to ensure that we always store content.
2049 $fields = $condition;
2052 logger('Update content for ' . json_encode($condition));
2054 DBA::update('item-content', $fields, $condition, true);
2058 * @brief Distributes public items to the receivers
2060 * @param integer $itemid Item ID that should be added
2061 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2063 public static function distribute($itemid, $signed_text = '')
2065 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2066 $parent = self::selectFirst(['owner-id'], $condition);
2067 if (!DBA::isResult($parent)) {
2071 // Only distribute public items from native networks
2072 $condition = ['id' => $itemid, 'uid' => 0,
2073 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2074 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2075 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2076 if (!DBA::isResult($item)) {
2080 $origin = $item['origin'];
2083 unset($item['parent']);
2084 unset($item['mention']);
2085 unset($item['wall']);
2086 unset($item['origin']);
2087 unset($item['starred']);
2091 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2092 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2093 if (!DBA::isResult($owner)) {
2097 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2098 $contacts = DBA::select('contact', ['uid'], $condition);
2099 while ($contact = DBA::fetch($contacts)) {
2100 if ($contact['uid'] == 0) {
2104 $users[$contact['uid']] = $contact['uid'];
2106 DBA::close($contacts);
2108 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2109 $contacts = DBA::select('contact', ['uid'], $condition);
2110 while ($contact = DBA::fetch($contacts)) {
2111 if ($contact['uid'] == 0) {
2115 $users[$contact['uid']] = $contact['uid'];
2117 DBA::close($contacts);
2119 if (!empty($owner['alias'])) {
2120 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2121 $contacts = DBA::select('contact', ['uid'], $condition);
2122 while ($contact = DBA::fetch($contacts)) {
2123 if ($contact['uid'] == 0) {
2127 $users[$contact['uid']] = $contact['uid'];
2129 DBA::close($contacts);
2134 if ($item['uri'] != $item['parent-uri']) {
2135 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2136 while ($parent = self::fetch($parents)) {
2137 $users[$parent['uid']] = $parent['uid'];
2138 if ($parent['origin'] && !$origin) {
2139 $origin_uid = $parent['uid'];
2144 foreach ($users as $uid) {
2145 if ($origin_uid == $uid) {
2146 $item['diaspora_signed_text'] = $signed_text;
2148 self::storeForUser($itemid, $item, $uid);
2153 * @brief Store public items for the receivers
2155 * @param integer $itemid Item ID that should be added
2156 * @param array $item The item entry that will be stored
2157 * @param integer $uid The user that will receive the item entry
2159 private static function storeForUser($itemid, $item, $uid)
2161 $item['uid'] = $uid;
2162 $item['origin'] = 0;
2164 if ($item['uri'] == $item['parent-uri']) {
2165 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2167 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2170 if (empty($item['contact-id'])) {
2171 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2172 if (!DBA::isResult($self)) {
2175 $item['contact-id'] = $self['id'];
2178 /// @todo Handling of "event-id"
2181 if ($item['uri'] == $item['parent-uri']) {
2182 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2183 if (DBA::isResult($contact)) {
2184 $notify = self::isRemoteSelf($contact, $item);
2188 $distributed = self::insert($item, false, $notify, true);
2190 if (!$distributed) {
2191 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2193 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2198 * @brief Add a shadow entry for a given item id that is a thread starter
2200 * We store every public item entry additionally with the user id "0".
2201 * This is used for the community page and for the search.
2202 * It is planned that in the future we will store public item entries only once.
2204 * @param integer $itemid Item ID that should be added
2206 public static function addShadow($itemid)
2208 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2209 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2210 $item = self::selectFirst($fields, $condition);
2212 if (!DBA::isResult($item)) {
2216 // is it already a copy?
2217 if (($itemid == 0) || ($item['uid'] == 0)) {
2221 // Is it a visible public post?
2222 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2226 // is it an entry from a connector? Only add an entry for natively connected networks
2227 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2231 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2235 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2237 if (DBA::isResult($item)) {
2238 // Preparing public shadow (removing user specific data)
2241 unset($item['parent']);
2242 unset($item['wall']);
2243 unset($item['mention']);
2244 unset($item['origin']);
2245 unset($item['starred']);
2246 unset($item['postopts']);
2247 unset($item['inform']);
2248 if ($item['uri'] == $item['parent-uri']) {
2249 $item['contact-id'] = $item['owner-id'];
2251 $item['contact-id'] = $item['author-id'];
2254 $public_shadow = self::insert($item, false, false, true);
2256 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2261 * @brief Add a shadow entry for a given item id that is a comment
2263 * This function does the same like the function above - but for comments
2265 * @param integer $itemid Item ID that should be added
2267 public static function addShadowPost($itemid)
2269 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2270 if (!DBA::isResult($item)) {
2274 // Is it a toplevel post?
2275 if ($item['id'] == $item['parent']) {
2276 self::addShadow($itemid);
2280 // Is this a shadow entry?
2281 if ($item['uid'] == 0) {
2285 // Is there a shadow parent?
2286 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2290 // Is there already a shadow entry?
2291 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2295 // Save "origin" and "parent" state
2296 $origin = $item['origin'];
2297 $parent = $item['parent'];
2299 // Preparing public shadow (removing user specific data)
2302 unset($item['parent']);
2303 unset($item['wall']);
2304 unset($item['mention']);
2305 unset($item['origin']);
2306 unset($item['starred']);
2307 unset($item['postopts']);
2308 unset($item['inform']);
2309 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2311 $public_shadow = self::insert($item, false, false, true);
2313 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2315 // If this was a comment to a Diaspora post we don't get our comment back.
2316 // This means that we have to distribute the comment by ourselves.
2317 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2318 self::distribute($public_shadow);
2323 * Adds a language specification in a "language" element of given $arr.
2324 * Expects "body" element to exist in $arr.
2326 private static function addLanguageToItemArray(&$item)
2328 $naked_body = BBCode::toPlaintext($item['body'], false);
2330 $ld = new Text_LanguageDetect();
2331 $ld->setNameMode(2);
2332 $languages = $ld->detect($naked_body, 3);
2334 if (is_array($languages)) {
2335 $item['language'] = json_encode($languages);
2340 * @brief Creates an unique guid out of a given uri
2342 * @param string $uri uri of an item entry
2343 * @param string $host hostname for the GUID prefix
2344 * @return string unique guid
2346 public static function guidFromUri($uri, $host)
2348 // Our regular guid routine is using this kind of prefix as well
2349 // We have to avoid that different routines could accidentally create the same value
2350 $parsed = parse_url($uri);
2352 // We use a hash of the hostname as prefix for the guid
2353 $guid_prefix = hash("crc32", $host);
2355 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2356 unset($parsed["scheme"]);
2358 // Glue it together to be able to make a hash from it
2359 $host_id = implode("/", $parsed);
2361 // We could use any hash algorithm since it isn't a security issue
2362 $host_hash = hash("ripemd128", $host_id);
2364 return $guid_prefix.$host_hash;
2368 * generate an unique URI
2370 * @param integer $uid User id
2371 * @param string $guid An existing GUID (Otherwise it will be generated)
2375 public static function newURI($uid, $guid = "")
2378 $guid = System::createUUID();
2381 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2385 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2387 * This can be used to filter for inactive contacts.
2388 * Only do this for public postings to avoid privacy problems, since poco data is public.
2389 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2391 * @param array $arr Contains the just posted item record
2393 private static function updateContact($arr)
2395 // Unarchive the author
2396 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2397 if (DBA::isResult($contact)) {
2398 Contact::unmarkForArchival($contact);
2401 // Unarchive the contact if it's not our own contact
2402 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2403 if (DBA::isResult($contact)) {
2404 Contact::unmarkForArchival($contact);
2407 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2409 // Is it a forum? Then we don't care about the rules from above
2410 if (!$update && ($arr["network"] == Protocol::DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2411 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2417 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2418 ['id' => $arr['contact-id']]);
2420 // Now do the same for the system wide contacts with uid=0
2421 if (!$arr['private']) {
2422 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2423 ['id' => $arr['owner-id']]);
2425 if ($arr['owner-id'] != $arr['author-id']) {
2426 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2427 ['id' => $arr['author-id']]);
2432 public static function setHashtags(&$item)
2435 $tags = get_tags($item["body"]);
2438 if (!count($tags)) {
2442 // This sorting is important when there are hashtags that are part of other hashtags
2443 // Otherwise there could be problems with hashtags like #test and #test2
2446 $URLSearchString = "^\[\]";
2448 // All hashtags should point to the home server if "local_tags" is activated
2449 if (Config::get('system', 'local_tags')) {
2450 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2451 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2453 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2454 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2457 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2458 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2460 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2463 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2465 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2468 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2470 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2473 // Repair recursive urls
2474 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2475 "#$2", $item["body"]);
2477 foreach ($tags as $tag) {
2478 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2482 $basetag = str_replace('_',' ',substr($tag,1));
2484 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2486 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2488 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2489 if (strlen($item["tag"])) {
2490 $item["tag"] = ','.$item["tag"];
2492 $item["tag"] = $newtag.$item["tag"];
2496 // Convert back the masked hashtags
2497 $item["body"] = str_replace("#", "#", $item["body"]);
2500 public static function getGuidById($id)
2502 $item = self::selectFirst(['guid'], ['id' => $id]);
2503 if (DBA::isResult($item)) {
2504 return $item['guid'];
2511 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2512 * @param string $guid item guid
2513 * @param int $uid user id
2514 * @return array with id and nick of the item with the given guid
2516 public static function getIdAndNickByGuid($guid, $uid = 0)
2522 $uid == local_user();
2525 // Does the given user have this item?
2527 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2528 if (DBA::isResult($item)) {
2529 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2530 if (!DBA::isResult($user)) {
2534 $nick = $user['nickname'];
2538 // Or is it anywhere on the server?
2540 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2541 $item = self::selectFirst(['id', 'uid'], $condition);
2542 if (DBA::isResult($item)) {
2543 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2544 if (!DBA::isResult($user)) {
2548 $nick = $user['nickname'];
2551 return ["nick" => $nick, "id" => $id];
2555 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2557 * @param int $item_id
2558 * @return bool true if item was deleted, else false
2560 private static function tagDeliver($uid, $item_id)
2564 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2565 if (!DBA::isResult($user)) {
2569 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2570 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2572 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2573 if (!DBA::isResult($item)) {
2577 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2580 * Diaspora uses their own hardwired link URL in @-tags
2581 * instead of the one we supply with webfinger
2583 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2585 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2587 foreach ($matches as $mtch) {
2588 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2590 logger('mention found: ' . $mtch[2]);
2596 if (($community_page || $prvgroup) &&
2597 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2598 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2600 logger("no-mention top-level post to community or private group. delete.");
2601 DBA::delete('item', ['id' => $item_id]);
2607 $arr = ['item' => $item, 'user' => $user];
2609 Addon::callHooks('tagged', $arr);
2611 if (!$community_page && !$prvgroup) {
2616 * tgroup delivery - setup a second delivery chain
2617 * prevent delivery looping - only proceed
2618 * if the message originated elsewhere and is a top-level post
2620 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2624 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2625 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2626 if (!DBA::isResult($self)) {
2630 $owner_id = Contact::getIdForURL($self['url']);
2632 // also reset all the privacy bits to the forum default permissions
2634 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2636 $psid = PermissionSet::fetchIDForPost($user);
2638 $forum_mode = ($prvgroup ? 2 : 1);
2640 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2641 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2642 self::update($fields, ['id' => $item_id]);
2644 self::updateThread($item_id);
2646 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2649 public static function isRemoteSelf($contact, &$datarray)
2653 if (!$contact['remote_self']) {
2657 // Prevent the forwarding of posts that are forwarded
2658 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2659 logger('Already forwarded', LOGGER_DEBUG);
2663 // Prevent to forward already forwarded posts
2664 if ($datarray["app"] == $a->getHostName()) {
2665 logger('Already forwarded (second test)', LOGGER_DEBUG);
2669 // Only forward posts
2670 if ($datarray["verb"] != ACTIVITY_POST) {
2671 logger('No post', LOGGER_DEBUG);
2675 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2676 logger('Not public', LOGGER_DEBUG);
2680 $datarray2 = $datarray;
2681 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2682 if ($contact['remote_self'] == 2) {
2683 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2684 ['uid' => $contact['uid'], 'self' => true]);
2685 if (DBA::isResult($self)) {
2686 $datarray['contact-id'] = $self["id"];
2688 $datarray['owner-name'] = $self["name"];
2689 $datarray['owner-link'] = $self["url"];
2690 $datarray['owner-avatar'] = $self["thumb"];
2692 $datarray['author-name'] = $datarray['owner-name'];
2693 $datarray['author-link'] = $datarray['owner-link'];
2694 $datarray['author-avatar'] = $datarray['owner-avatar'];
2696 unset($datarray['created']);
2697 unset($datarray['edited']);
2699 unset($datarray['network']);
2700 unset($datarray['owner-id']);
2701 unset($datarray['author-id']);
2704 if ($contact['network'] != Protocol::FEED) {
2705 $datarray["guid"] = System::createUUID();
2706 unset($datarray["plink"]);
2707 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2708 $datarray["parent-uri"] = $datarray["uri"];
2709 $datarray["thr-parent"] = $datarray["uri"];
2710 $datarray["extid"] = Protocol::DFRN;
2711 $urlpart = parse_url($datarray2['author-link']);
2712 $datarray["app"] = $urlpart["host"];
2714 $datarray['private'] = 0;
2718 if ($contact['network'] != Protocol::FEED) {
2719 // Store the original post
2720 $result = self::insert($datarray2, false, false);
2721 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2723 $datarray["app"] = "Feed";
2727 // Trigger automatic reactions for addons
2728 $datarray['api_source'] = true;
2730 // We have to tell the hooks who we are - this really should be improved
2731 $_SESSION["authenticated"] = true;
2732 $_SESSION["uid"] = $contact['uid'];
2741 * @param array $item
2745 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2747 if (Config::get('system', 'disable_embedded')) {
2751 logger('check for photos', LOGGER_DEBUG);
2752 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2757 $img_start = strpos($orig_body, '[img');
2758 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2759 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2761 while (($img_st_close !== false) && ($img_len !== false)) {
2762 $img_st_close++; // make it point to AFTER the closing bracket
2763 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2765 logger('found photo ' . $image, LOGGER_DEBUG);
2767 if (stristr($image, $site . '/photo/')) {
2768 // Only embed locally hosted photos
2770 $i = basename($image);
2771 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2772 $x = strpos($i, '-');
2775 $res = substr($i, $x + 1);
2776 $i = substr($i, 0, $x);
2777 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2778 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2779 if (DBA::isResult($photo)) {
2781 * Check to see if we should replace this photo link with an embedded image
2782 * 1. No need to do so if the photo is public
2783 * 2. If there's a contact-id provided, see if they're in the access list
2784 * for the photo. If so, embed it.
2785 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2786 * permissions, regardless of order but first check to see if they're an exact
2787 * match to save some processing overhead.
2789 if (self::hasPermissions($photo)) {
2791 $recips = self::enumeratePermissions($photo);
2792 if (in_array($cid, $recips)) {
2796 if (self::samePermissions($item, $photo)) {
2802 $data = $photo['data'];
2803 $type = $photo['type'];
2805 // If a custom width and height were specified, apply before embedding
2806 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2807 logger('scaling photo', LOGGER_DEBUG);
2809 $width = intval($match[1]);
2810 $height = intval($match[2]);
2812 $Image = new Image($data, $type);
2813 if ($Image->isValid()) {
2814 $Image->scaleDown(max($width, $height));
2815 $data = $Image->asString();
2816 $type = $Image->getType();
2820 logger('replacing photo', LOGGER_DEBUG);
2821 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2822 logger('replaced: ' . $image, LOGGER_DATA);
2828 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2829 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2830 if ($orig_body === false) {
2834 $img_start = strpos($orig_body, '[img');
2835 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2836 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2839 $new_body = $new_body . $orig_body;
2844 private static function hasPermissions($obj)
2846 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2847 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2850 private static function samePermissions($obj1, $obj2)
2852 // first part is easy. Check that these are exactly the same.
2853 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2854 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2855 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2856 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2860 // This is harder. Parse all the permissions and compare the resulting set.
2861 $recipients1 = self::enumeratePermissions($obj1);
2862 $recipients2 = self::enumeratePermissions($obj2);
2866 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2867 return ($recipients1 == $recipients2);
2870 // returns an array of contact-ids that are allowed to see this object
2871 public static function enumeratePermissions($obj)
2873 $allow_people = expand_acl($obj['allow_cid']);
2874 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2875 $deny_people = expand_acl($obj['deny_cid']);
2876 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2877 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2878 $deny = array_unique(array_merge($deny_people, $deny_groups));
2879 $recipients = array_diff($recipients, $deny);
2883 public static function getFeedTags($item)
2887 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2889 for ($x = 0; $x < $cnt; $x ++) {
2890 if ($matches[1][$x]) {
2891 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2896 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2898 for ($x = 0; $x < $cnt; $x ++) {
2899 if ($matches[1][$x]) {
2900 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2907 public static function expire($uid, $days, $network = "", $force = false)
2909 if (!$uid || ($days < 1)) {
2913 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2914 $uid, GRAVITY_PARENT];
2917 * $expire_network_only = save your own wall posts
2918 * and just expire conversations started by others
2920 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2922 if ($expire_network_only) {
2923 $condition[0] .= " AND NOT `wall`";
2926 if ($network != "") {
2927 $condition[0] .= " AND `network` = ?";
2928 $condition[] = $network;
2931 * There is an index "uid_network_received" but not "uid_network_created"
2932 * This avoids the creation of another index just for one purpose.
2933 * And it doesn't really matter wether to look at "received" or "created"
2935 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2936 $condition[] = $days;
2938 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2939 $condition[] = $days;
2942 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2944 if (!DBA::isResult($items)) {
2948 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2950 // Forcing expiring of items - but not notes and marked items
2952 $expire_items = true;
2955 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2956 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2957 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2961 while ($item = Item::fetch($items)) {
2962 // don't expire filed items
2964 if (strpos($item['file'], '[') !== false) {
2968 // Only expire posts, not photos and photo comments
2970 if (!$expire_photos && strlen($item['resource-id'])) {
2972 } elseif (!$expire_starred && intval($item['starred'])) {
2974 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2976 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2980 self::deleteById($item['id'], PRIORITY_LOW);
2985 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2988 public static function firstPostDate($uid, $wall = false)
2990 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2991 $params = ['order' => ['created' => false]];
2992 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2993 if (DBA::isResult($thread)) {
2994 return substr(DateTimeFormat::local($thread['created']), 0, 10);
3000 * @brief add/remove activity to an item
3002 * Toggle activities as like,dislike,attend of an item
3004 * @param string $item_id
3005 * @param string $verb
3006 * Activity verb. One of
3007 * like, unlike, dislike, undislike, attendyes, unattendyes,
3008 * attendno, unattendno, attendmaybe, unattendmaybe
3009 * @hook 'post_local_end'
3011 * 'post_id' => ID of posted item
3013 public static function performLike($item_id, $verb)
3015 if (!local_user() && !remote_user()) {
3022 $activity = ACTIVITY_LIKE;
3026 $activity = ACTIVITY_DISLIKE;
3030 $activity = ACTIVITY_ATTEND;
3034 $activity = ACTIVITY_ATTENDNO;
3037 case 'unattendmaybe':
3038 $activity = ACTIVITY_ATTENDMAYBE;
3041 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
3045 // Enable activity toggling instead of on/off
3046 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3048 logger('like: verb ' . $verb . ' item ' . $item_id);
3050 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3051 if (!DBA::isResult($item)) {
3052 logger('like: unknown item ' . $item_id);
3056 $item_uri = $item['uri'];
3058 $uid = $item['uid'];
3059 if (($uid == 0) && local_user()) {
3060 $uid = local_user();
3063 if (!can_write_wall($uid)) {
3064 logger('like: unable to write on wall ' . $uid);
3068 // Retrieves the local post owner
3069 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3070 if (!DBA::isResult($owner_self_contact)) {
3071 logger('like: unknown owner ' . $uid);
3075 // Retrieve the current logged in user's public contact
3076 $author_id = public_contact();
3078 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3079 if (!DBA::isResult($author_contact)) {
3080 logger('like: unknown author ' . $author_id);
3084 // Contact-id is the uid-dependant author contact
3085 if (local_user() == $uid) {
3086 $item_contact_id = $owner_self_contact['id'];
3087 $item_contact = $owner_self_contact;
3089 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3090 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3091 if (!DBA::isResult($item_contact)) {
3092 logger('like: unknown item contact ' . $item_contact_id);
3097 // Look for an existing verb row
3098 // event participation are essentially radio toggles. If you make a subsequent choice,
3099 // we need to eradicate your first choice.
3100 if ($event_verb_flag) {
3101 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3103 // Translate to the index based activity index
3105 foreach ($verbs as $verb) {
3106 $activities[] = self::activityToIndex($verb);
3109 $activities = self::activityToIndex($activity);
3112 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3113 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3115 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3117 // If it exists, mark it as deleted
3118 if (DBA::isResult($like_item)) {
3119 self::deleteById($like_item['id']);
3121 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3126 // Verb is "un-something", just trying to delete existing entries
3127 if (strpos($verb, 'un') === 0) {
3131 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3134 'guid' => System::createUUID(),
3135 'uri' => self::newURI($item['uid']),
3136 'uid' => $item['uid'],
3137 'contact-id' => $item_contact_id,
3138 'wall' => $item['wall'],
3140 'network' => Protocol::DFRN,
3141 'gravity' => GRAVITY_ACTIVITY,
3142 'parent' => $item['id'],
3143 'parent-uri' => $item['uri'],
3144 'thr-parent' => $item['uri'],
3145 'owner-id' => $author_id,
3146 'author-id' => $author_id,
3147 'body' => $activity,
3148 'verb' => $activity,
3149 'object-type' => $objtype,
3150 'allow_cid' => $item['allow_cid'],
3151 'allow_gid' => $item['allow_gid'],
3152 'deny_cid' => $item['deny_cid'],
3153 'deny_gid' => $item['deny_gid'],
3158 $new_item_id = self::insert($new_item);
3160 // If the parent item isn't visible then set it to visible
3161 if (!$item['visible']) {
3162 self::update(['visible' => true], ['id' => $item['id']]);
3165 // Save the author information for the like in case we need to relay to Diaspora
3166 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3168 $new_item['id'] = $new_item_id;
3170 Addon::callHooks('post_local_end', $new_item);
3172 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3177 private static function addThread($itemid, $onlyshadow = false)
3179 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3180 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3181 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3182 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3183 $item = self::selectFirst($fields, $condition);
3185 if (!DBA::isResult($item)) {
3189 $item['iid'] = $itemid;
3192 $result = DBA::insert('thread', $item);
3194 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3198 private static function updateThread($itemid, $setmention = false)
3200 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3201 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3202 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3203 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3205 $item = self::selectFirst($fields, $condition);
3206 if (!DBA::isResult($item)) {
3211 $item["mention"] = 1;
3218 foreach ($item as $field => $data) {
3219 if (!in_array($field, ["guid"])) {
3220 $fields[$field] = $data;
3224 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3226 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3229 private static function deleteThread($itemid, $itemuri = "")
3231 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3232 if (!DBA::isResult($item)) {
3233 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3237 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3239 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3241 if ($itemuri != "") {
3242 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3243 if (!self::exists($condition)) {
3244 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3245 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);