4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Map;
27 use Friendica\Util\XML;
28 use Friendica\Util\Security;
29 use Friendica\Util\Strings;
30 use Text_LanguageDetect;
32 class Item extends BaseObject
34 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
41 const PT_DOCUMENT = 19;
43 const PT_PERSONAL_NOTE = 128;
45 // Field list that is used to display the items
46 const DISPLAY_FIELDLIST = [
47 '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',
59 'delivery_queue_count', 'delivery_queue_done'
62 // Field list that is used to deliver items via the protocols
63 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
64 'created', 'edited', 'verb', 'object-type', 'object', 'target',
65 'private', 'title', 'body', 'location', 'coord', 'app',
66 'attach', 'tag', 'deleted', 'extid', 'post-type',
67 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
68 'author-id', 'author-link', 'owner-link', 'contact-uid',
69 'signed_text', 'signature', 'signer', 'network'];
71 // Field list for "item-content" table that is mixed with the item table
72 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
73 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
74 'object-type', 'object', 'target-type', 'target', 'plink'];
76 // Field list for "item-content" table that is not present in the "item" table
77 const CONTENT_FIELDLIST = ['language'];
79 // All fields in the item table
80 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
81 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
82 'created', 'edited', 'commented', 'received', 'changed', 'verb',
83 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
84 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
85 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
86 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
87 'title', 'content-warning', 'body', 'location', 'coord', 'app',
88 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
89 'author-id', 'author-link', 'author-name', 'author-avatar',
90 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
92 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
93 // The item-activity table only stores the index and needs this array to know the matching activity.
94 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
96 private static $legacy_mode = null;
98 public static function isLegacyMode()
100 if (is_null(self::$legacy_mode)) {
101 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
104 return self::$legacy_mode;
108 * @brief returns an activity index from an activity string
110 * @param string $activity activity string
111 * @return integer Activity index
113 public static function activityToIndex($activity)
115 $index = array_search($activity, self::ACTIVITIES);
117 if (is_bool($index)) {
125 * @brief returns an activity string from an activity index
127 * @param integer $index activity index
128 * @return string Activity string
130 private static function indexToActivity($index)
132 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
136 return self::ACTIVITIES[$index];
140 * @brief Fetch a single item row
142 * @param mixed $stmt statement object
143 * @return array current row
145 public static function fetch($stmt)
147 $row = DBA::fetch($stmt);
153 // ---------------------- Transform item structure data ----------------------
155 // We prefer the data from the user's contact over the public one
156 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
157 ($row['author-link'] == $row['contact-link'])) {
158 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
159 $row['author-avatar'] = $row['contact-avatar'];
161 if (isset($row['author-name']) && !empty($row['contact-name'])) {
162 $row['author-name'] = $row['contact-name'];
166 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
167 ($row['owner-link'] == $row['contact-link'])) {
168 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
169 $row['owner-avatar'] = $row['contact-avatar'];
171 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
172 $row['owner-name'] = $row['contact-name'];
176 // We can always comment on posts from these networks
177 if (array_key_exists('writable', $row) &&
178 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
179 $row['writable'] = true;
182 // ---------------------- Transform item content data ----------------------
184 // Fetch data from the item-content table whenever there is content there
185 if (self::isLegacyMode()) {
186 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
187 foreach ($legacy_fields as $field) {
188 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
189 $row[$field] = $row['internal-item-' . $field];
191 unset($row['internal-item-' . $field]);
195 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
196 $row['verb'] = self::indexToActivity($row['internal-activity']);
197 if (array_key_exists('title', $row)) {
200 if (array_key_exists('body', $row)) {
201 $row['body'] = $row['verb'];
203 if (array_key_exists('object', $row)) {
206 if (array_key_exists('object-type', $row)) {
207 $row['object-type'] = ACTIVITY_OBJ_NOTE;
209 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
210 // Posts don't have an object or target - but having tags or files.
211 // We safe some performance by building tag and file strings only here.
212 // We remove object and target since they aren't used for this type.
213 if (array_key_exists('object', $row)) {
216 if (array_key_exists('target', $row)) {
221 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
222 // Build the tag string out of the term entries
223 if (array_key_exists('tag', $row) && empty($row['tag'])) {
224 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
227 // Build the file string out of the term entries
228 if (array_key_exists('file', $row) && empty($row['file'])) {
229 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
233 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
234 $row['signed_text'] = $row['interaction'];
237 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
238 $row['ignored'] = $row['internal-user-ignored'];
241 // Remove internal fields
242 unset($row['internal-activity']);
243 unset($row['internal-network']);
244 unset($row['internal-iid']);
245 unset($row['internal-iaid']);
246 unset($row['internal-icid']);
247 unset($row['internal-user-ignored']);
248 unset($row['interaction']);
254 * @brief Fills an array with data from an item query
256 * @param object $stmt statement object
257 * @param bool $do_close
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?
283 public static function exists($condition) {
284 $stmt = self::select(['id'], $condition, ['limit' => 1]);
286 if (is_bool($stmt)) {
289 $retval = (DBA::numRows($stmt) > 0);
298 * Retrieve a single record from the item table for a given user and returns it in an associative array
300 * @brief Retrieve a single record from a table
301 * @param integer $uid User ID
302 * @param array $selected
303 * @param array $condition
304 * @param array $params
309 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
311 $params['uid'] = $uid;
313 if (empty($selected)) {
314 $selected = Item::DISPLAY_FIELDLIST;
317 return self::selectFirst($selected, $condition, $params);
321 * @brief Select rows from the item table for a given user
323 * @param integer $uid User ID
324 * @param array $selected Array of selected fields, empty for all
325 * @param array $condition Array of fields for condition
326 * @param array $params Array of several parameters
328 * @return boolean|object
331 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
333 $params['uid'] = $uid;
335 if (empty($selected)) {
336 $selected = Item::DISPLAY_FIELDLIST;
339 return self::select($selected, $condition, $params);
343 * Retrieve a single record from the item table and returns it in an associative array
345 * @brief Retrieve a single record from a table
346 * @param array $fields
347 * @param array $condition
348 * @param array $params
353 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
355 $params['limit'] = 1;
357 $result = self::select($fields, $condition, $params);
359 if (is_bool($result)) {
362 $row = self::fetch($result);
369 * @brief Select rows from the item table
371 * @param array $selected Array of selected fields, empty for all
372 * @param array $condition Array of fields for condition
373 * @param array $params Array of several parameters
375 * @return boolean|object
378 public static function select(array $selected = [], array $condition = [], $params = [])
383 if (isset($params['uid'])) {
384 $uid = $params['uid'];
388 $fields = self::fieldlist($usermode);
390 $select_fields = self::constructSelectFields($fields, $selected);
392 $condition_string = DBA::buildCondition($condition);
394 $condition_string = self::addTablesToFields($condition_string, $fields);
397 $condition_string = $condition_string . ' AND ' . self::condition(false);
400 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
402 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
404 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
406 return DBA::p($sql, $condition);
410 * @brief Select rows from the starting post in the item table
412 * @param integer $uid User ID
413 * @param array $selected
414 * @param array $condition Array of fields for condition
415 * @param array $params Array of several parameters
417 * @return boolean|object
420 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
422 $params['uid'] = $uid;
424 if (empty($selected)) {
425 $selected = Item::DISPLAY_FIELDLIST;
428 return self::selectThread($selected, $condition, $params);
432 * Retrieve a single record from the starting post in the item table and returns it in an associative array
434 * @brief Retrieve a single record from a table
435 * @param integer $uid User ID
436 * @param array $selected
437 * @param array $condition
438 * @param array $params
443 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
445 $params['uid'] = $uid;
447 if (empty($selected)) {
448 $selected = Item::DISPLAY_FIELDLIST;
451 return self::selectFirstThread($selected, $condition, $params);
455 * Retrieve a single record from the starting post in the item table and returns it in an associative array
457 * @brief Retrieve a single record from a table
458 * @param array $fields
459 * @param array $condition
460 * @param array $params
465 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
467 $params['limit'] = 1;
468 $result = self::selectThread($fields, $condition, $params);
470 if (is_bool($result)) {
473 $row = self::fetch($result);
480 * @brief Select rows from the starting post in the item table
482 * @param array $selected Array of selected fields, empty for all
483 * @param array $condition Array of fields for condition
484 * @param array $params Array of several parameters
486 * @return boolean|object
489 public static function selectThread(array $selected = [], array $condition = [], $params = [])
494 if (isset($params['uid'])) {
495 $uid = $params['uid'];
499 $fields = self::fieldlist($usermode);
501 $fields['thread'] = ['mention', 'ignored', 'iid'];
503 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
504 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
505 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
506 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
508 $select_fields = self::constructSelectFields($fields, $selected);
510 $condition_string = DBA::buildCondition($condition);
512 $condition_string = self::addTablesToFields($condition_string, $threadfields);
513 $condition_string = self::addTablesToFields($condition_string, $fields);
516 $condition_string = $condition_string . ' AND ' . self::condition(true);
519 $param_string = DBA::buildParameter($params);
520 $param_string = self::addTablesToFields($param_string, $threadfields);
521 $param_string = self::addTablesToFields($param_string, $fields);
523 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
525 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
527 return DBA::p($sql, $condition);
531 * @brief Returns a list of fields that are associated with the item table
534 * @return array field list
536 private static function fieldlist($usermode)
540 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
541 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
542 'created', 'edited', 'commented', 'received', 'changed', 'psid',
543 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
544 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
545 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
546 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
547 'network' => 'internal-network', 'icid' => 'internal-icid',
548 'iaid' => 'internal-iaid'];
551 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
554 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
556 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
558 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
560 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
562 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
563 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
565 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
566 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
568 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
569 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
570 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
572 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
574 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
576 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
577 'start' => 'event-start','finish' => 'event-finish',
578 'summary' => 'event-summary','desc' => 'event-desc',
579 'location' => 'event-location', 'type' => 'event-type',
580 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
581 'ignore' => 'event-ignore', 'id' => 'event-id'];
583 $fields['sign'] = ['signed_text', 'signature', 'signer'];
585 $fields['diaspora-interaction'] = ['interaction'];
591 * @brief Returns SQL condition for the "select" functions
593 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
595 * @return string SQL condition
597 private static function condition($thread_mode)
600 $master_table = "`thread`";
602 $master_table = "`item`";
604 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
605 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
606 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
607 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
608 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
609 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
610 GRAVITY_PARENT, GRAVITY_PARENT);
614 * @brief Returns all needed "JOIN" commands for the "select" functions
616 * @param integer $uid User ID
617 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
618 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
621 * @return string The SQL joins for the "select" functions
623 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
626 $master_table = "`thread`";
627 $master_table_key = "`thread`.`iid`";
628 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
630 $master_table = "`item`";
631 $master_table_key = "`item`.`id`";
636 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
637 AND NOT `contact`.`blocked`
638 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
639 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
640 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
641 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
642 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
643 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
644 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
645 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
647 if (strpos($sql_commands, "`contact`.") !== false) {
648 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
650 if (strpos($sql_commands, "`author`.") !== false) {
651 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
653 if (strpos($sql_commands, "`owner`.") !== false) {
654 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
658 if (strpos($sql_commands, "`group_member`.") !== false) {
659 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
662 if (strpos($sql_commands, "`user`.") !== false) {
663 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
666 if (strpos($sql_commands, "`event`.") !== false) {
667 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
670 if (strpos($sql_commands, "`sign`.") !== false) {
671 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
674 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
675 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
678 if (strpos($sql_commands, "`item-activity`.") !== false) {
679 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
682 if (strpos($sql_commands, "`item-content`.") !== false) {
683 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
686 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
687 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
690 if (strpos($sql_commands, "`permissionset`.") !== false) {
691 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
694 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
695 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
698 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
699 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
706 * @brief Add the field list for the "select" functions
708 * @param array $fields The field definition array
709 * @param array $selected The array with the selected fields from the "select" functions
711 * @return string The field list
713 private static function constructSelectFields($fields, $selected)
715 if (!empty($selected)) {
716 $selected[] = 'internal-iid';
717 $selected[] = 'internal-iaid';
718 $selected[] = 'internal-icid';
719 $selected[] = 'internal-network';
722 if (in_array('verb', $selected)) {
723 $selected[] = 'internal-activity';
726 if (in_array('ignored', $selected)) {
727 $selected[] = 'internal-user-ignored';
730 if (in_array('signed_text', $selected)) {
731 $selected[] = 'interaction';
734 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
737 foreach ($fields as $table => $table_fields) {
738 foreach ($table_fields as $field => $select) {
739 if (empty($selected) || in_array($select, $selected)) {
740 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
741 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
743 if (is_int($field)) {
744 $selection[] = "`" . $table . "`.`" . $select . "`";
746 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
751 return implode(", ", $selection);
755 * @brief add table definition to fields in an SQL query
757 * @param string $query SQL query
758 * @param array $fields The field definition array
760 * @return string the changed SQL query
762 private static function addTablesToFields($query, $fields)
764 foreach ($fields as $table => $table_fields) {
765 foreach ($table_fields as $alias => $field) {
766 if (is_int($alias)) {
767 $replace_field = $field;
769 $replace_field = $alias;
772 $search = "/([^\.])`" . $field . "`/i";
773 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
774 $query = preg_replace($search, $replace, $query);
781 * @brief Update existing item entries
783 * @param array $fields The fields that are to be changed
784 * @param array $condition The condition for finding the item entries
786 * In the future we may have to change permissions as well.
787 * Then we had to add the user id as third parameter.
789 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
791 * @return integer|boolean number of affected rows - or "false" if there was an error
792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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', 'uri-id', '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 $delivery_data = ItemDeliveryData::extractFields($fields);
822 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
823 foreach ($clear_fields as $field) {
824 if (array_key_exists($field, $fields)) {
825 $fields[$field] = null;
829 if (array_key_exists('tag', $fields)) {
830 $tags = $fields['tag'];
831 $fields['tag'] = null;
836 if (array_key_exists('file', $fields)) {
837 $files = $fields['file'];
838 $fields['file'] = null;
843 if (!empty($fields)) {
844 $success = DBA::update('item', $fields, $condition);
853 // When there is no content for the "old" item table, this will count the fetched items
854 $rows = DBA::affectedRows();
856 while ($item = DBA::fetch($items)) {
857 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
858 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
860 if (empty($item['iaid'])) {
861 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
862 if (DBA::isResult($item_activity)) {
863 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
864 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
865 if (self::isLegacyMode()) {
866 $item_fields[$field] = null;
868 unset($item_fields[$field]);
871 DBA::update('item', $item_fields, ['id' => $item['id']]);
873 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
874 DBA::delete('item-content', ['id' => $item['icid']]);
877 } elseif (!empty($item['icid'])) {
878 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
880 if (!DBA::exists('item', ['icid' => $item['icid']])) {
881 DBA::delete('item-content', ['id' => $item['icid']]);
885 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
887 if (empty($item['icid'])) {
888 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
889 if (DBA::isResult($item_content)) {
890 $item_fields = ['icid' => $item_content['id']];
891 // Clear all fields in the item table that have a content in the item-content table
892 foreach ($item_content as $field => $content) {
893 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
894 if (self::isLegacyMode()) {
895 $item_fields[$field] = null;
897 unset($item_fields[$field]);
901 DBA::update('item', $item_fields, ['id' => $item['id']]);
906 if (!is_null($tags)) {
907 Term::insertFromTagFieldByItemId($item['id'], $tags);
908 if (!empty($item['tag'])) {
909 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
913 if (!is_null($files)) {
914 Term::insertFromFileFieldByItemId($item['id'], $files);
915 if (!empty($item['file'])) {
916 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
920 ItemDeliveryData::update($item['id'], $delivery_data);
922 self::updateThread($item['id']);
924 // We only need to notfiy others when it is an original entry from us.
925 // Only call the notifier when the item has some content relevant change.
926 if ($item['origin'] && in_array('edited', array_keys($fields))) {
927 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
937 * @brief Delete an item and notify others about it - if it was ours
939 * @param array $condition The condition for finding the item entries
940 * @param integer $priority Priority for the notification
941 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
943 public static function delete($condition, $priority = PRIORITY_HIGH)
945 $items = self::select(['id'], $condition);
946 while ($item = self::fetch($items)) {
947 self::deleteById($item['id'], $priority);
953 * @brief Delete an item for an user and notify others about it - if it was ours
955 * @param array $condition The condition for finding the item entries
956 * @param integer $uid User who wants to delete this item
957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
959 public static function deleteForUser($condition, $uid)
965 $items = self::select(['id', 'uid'], $condition);
966 while ($item = self::fetch($items)) {
967 // "Deleting" global items just means hiding them
968 if ($item['uid'] == 0) {
969 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
970 } elseif ($item['uid'] == $uid) {
971 self::deleteById($item['id'], PRIORITY_HIGH);
973 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
980 * @brief Delete an item and notify others about it - if it was ours
982 * @param integer $item_id Item ID that should be delete
983 * @param integer $priority Priority for the notification
985 * @return boolean success
986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
990 // locate item to be deleted
991 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
992 'deleted', 'file', 'resource-id', 'event-id', 'attach',
993 'verb', 'object-type', 'object', 'target', 'contact-id',
994 'icid', 'iaid', 'psid'];
995 $item = self::selectFirst($fields, ['id' => $item_id]);
996 if (!DBA::isResult($item)) {
997 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1001 if ($item['deleted']) {
1002 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1006 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1007 if (!DBA::isResult($parent)) {
1008 $parent = ['origin' => false];
1011 // clean up categories and tags so they don't end up as orphans
1014 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1017 foreach ($matches as $mtch) {
1018 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1024 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1027 foreach ($matches as $mtch) {
1028 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1033 * If item is a link to a photo resource, nuke all the associated photos
1034 * (visitors will not have photo resources)
1035 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1036 * generate a resource-id and therefore aren't intimately linked to the item.
1038 /// @TODO: this should first check if photo is used elsewhere
1039 if (strlen($item['resource-id'])) {
1040 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1043 // If item is a link to an event, delete the event.
1044 if (intval($item['event-id'])) {
1045 Event::delete($item['event-id']);
1048 // If item has attachments, drop them
1049 /// @TODO: this should first check if attachment is used elsewhere
1050 foreach (explode(",", $item['attach']) as $attach) {
1051 preg_match("|attach/(\d+)|", $attach, $matches);
1052 if (is_array($matches) && count($matches) > 1) {
1053 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1057 // Delete tags that had been attached to other items
1058 self::deleteTagsFromItem($item);
1060 // Set the item to "deleted"
1061 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1062 DBA::update('item', $item_fields, ['id' => $item['id']]);
1064 Term::insertFromTagFieldByItemId($item['id'], '');
1065 Term::insertFromFileFieldByItemId($item['id'], '');
1066 self::deleteThread($item['id'], $item['parent-uri']);
1068 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1069 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1072 ItemDeliveryData::delete($item['id']);
1074 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1076 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1077 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1079 // When the permission set will be used in photo and events as well,
1080 // this query here needs to be extended.
1081 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1082 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1085 // If it's the parent of a comment thread, kill all the kids
1086 if ($item['id'] == $item['parent']) {
1087 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1090 // Is it our comment and/or our thread?
1091 if ($item['origin'] || $parent['origin']) {
1093 // When we delete the original post we will delete all existing copies on the server as well
1094 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1096 // send the notification upstream/downstream
1097 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1098 } elseif ($item['uid'] != 0) {
1100 // When we delete just our local user copy of an item, we have to set a marker to hide it
1101 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1102 if (DBA::isResult($global_item)) {
1103 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1107 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1112 private static function deleteTagsFromItem($item)
1114 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1118 $xo = XML::parseString($item["object"], false);
1119 $xt = XML::parseString($item["target"], false);
1121 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1125 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1126 if (!DBA::isResult($i)) {
1130 // For tags, the owner cannot remove the tag on the author's copy of the post.
1131 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1132 $author_copy = $item["origin"];
1134 if (($owner_remove && $author_copy) || !$owner_remove) {
1138 $tags = explode(',', $i["tag"]);
1141 foreach ($tags as $tag) {
1142 if (trim($tag) !== trim($xo->body)) {
1143 $newtags[] = trim($tag);
1147 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1150 private static function guid($item, $notify)
1152 if (!empty($item['guid'])) {
1153 return Strings::escapeTags(trim($item['guid']));
1157 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1158 // We add the hash of our own host because our host is the original creator of the post.
1159 $prefix_host = \get_app()->getHostName();
1163 // We are only storing the post so we create a GUID from the original hostname.
1164 if (!empty($item['author-link'])) {
1165 $parsed = parse_url($item['author-link']);
1166 if (!empty($parsed['host'])) {
1167 $prefix_host = $parsed['host'];
1171 if (empty($prefix_host) && !empty($item['plink'])) {
1172 $parsed = parse_url($item['plink']);
1173 if (!empty($parsed['host'])) {
1174 $prefix_host = $parsed['host'];
1178 if (empty($prefix_host) && !empty($item['uri'])) {
1179 $parsed = parse_url($item['uri']);
1180 if (!empty($parsed['host'])) {
1181 $prefix_host = $parsed['host'];
1185 // Is it in the format data@host.tld? - Used for mail contacts
1186 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1187 $mailparts = explode('@', $item['author-link']);
1188 $prefix_host = array_pop($mailparts);
1192 if (!empty($item['plink'])) {
1193 $guid = self::guidFromUri($item['plink'], $prefix_host);
1194 } elseif (!empty($item['uri'])) {
1195 $guid = self::guidFromUri($item['uri'], $prefix_host);
1197 $guid = System::createUUID(hash('crc32', $prefix_host));
1203 private static function contactId($item)
1205 $contact_id = (int)$item["contact-id"];
1207 if (!empty($contact_id)) {
1210 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1212 * First we are looking for a suitable contact that matches with the author of the post
1213 * This is done only for comments
1215 if ($item['parent-uri'] != $item['uri']) {
1216 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1219 // If not present then maybe the owner was found
1220 if ($contact_id == 0) {
1221 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1224 // Still missing? Then use the "self" contact of the current user
1225 if ($contact_id == 0) {
1226 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1227 if (DBA::isResult($self)) {
1228 $contact_id = $self["id"];
1231 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1236 // This function will finally cover most of the preparation functionality in mod/item.php
1237 public static function prepare(&$item)
1240 * @TODO: Unused code triggering inspection errors
1242 $data = BBCode::getAttachmentData($item['body']);
1243 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1244 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1245 $posttype = Item::PT_PAGE;
1246 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1251 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1255 $priority = PRIORITY_HIGH;
1257 // If it is a posting where users should get notifications, then define it as wall posting
1260 $item['origin'] = 1;
1261 $item['network'] = Protocol::DFRN;
1262 $item['protocol'] = Conversation::PARCEL_DFRN;
1264 if (is_int($notify)) {
1265 $priority = $notify;
1268 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1271 $item['guid'] = self::guid($item, $notify);
1272 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1275 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1277 // Store conversation data
1278 $item = Conversation::insert($item);
1281 * If a Diaspora signature structure was passed in, pull it out of the
1282 * item array and set it aside for later storage.
1286 if (isset($item['dsprsig'])) {
1287 $encoded_signature = $item['dsprsig'];
1288 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1289 unset($item['dsprsig']);
1292 $diaspora_signed_text = '';
1293 if (isset($item['diaspora_signed_text'])) {
1294 $diaspora_signed_text = $item['diaspora_signed_text'];
1295 unset($item['diaspora_signed_text']);
1298 // Converting the plink
1299 /// @TODO Check if this is really still needed
1300 if ($item['network'] == Protocol::OSTATUS) {
1301 if (isset($item['plink'])) {
1302 $item['plink'] = OStatus::convertHref($item['plink']);
1303 } elseif (isset($item['uri'])) {
1304 $item['plink'] = OStatus::convertHref($item['uri']);
1308 if (!empty($item['thr-parent'])) {
1309 $item['parent-uri'] = $item['thr-parent'];
1312 if (isset($item['gravity'])) {
1313 $item['gravity'] = intval($item['gravity']);
1314 } elseif ($item['parent-uri'] === $item['uri']) {
1315 $item['gravity'] = GRAVITY_PARENT;
1316 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1317 $item['gravity'] = GRAVITY_COMMENT;
1318 } elseif (activity_match($item['verb'], ACTIVITY_FOLLOW)) {
1319 $item['gravity'] = GRAVITY_ACTIVITY;
1321 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1322 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1325 $uid = intval($item['uid']);
1327 // check for create date and expire time
1328 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1330 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1331 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1332 $expire_interval = $user['expire'];
1335 if (($expire_interval > 0) && !empty($item['created'])) {
1336 $expire_date = time() - ($expire_interval * 86400);
1337 $created_date = strtotime($item['created']);
1338 if ($created_date < $expire_date) {
1339 Logger::notice('Item created before expiration interval.', [
1340 'created' => date('c', $created_date),
1341 'expired' => date('c', $expire_date),
1349 * Do we already have this item?
1350 * We have to check several networks since Friendica posts could be repeated
1351 * via OStatus (maybe Diasporsa as well)
1353 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1354 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1355 trim($item['uri']), $item['uid'],
1356 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1357 $existing = self::selectFirst(['id', 'network'], $condition);
1358 if (DBA::isResult($existing)) {
1359 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1361 Logger::notice('Item already existed for user', [
1362 'uri' => $item['uri'],
1364 'network' => $item['network'],
1365 'existing_id' => $existing["id"],
1366 'existing_network' => $existing["network"]
1370 return $existing["id"];
1374 $item['wall'] = intval(defaults($item, 'wall', 0));
1375 $item['extid'] = trim(defaults($item, 'extid', ''));
1376 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1377 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1378 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1379 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1380 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1381 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1382 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1383 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1384 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1385 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1386 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1387 $item['title'] = trim(defaults($item, 'title', ''));
1388 $item['location'] = trim(defaults($item, 'location', ''));
1389 $item['coord'] = trim(defaults($item, 'coord', ''));
1390 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1391 $item['deleted'] = 0;
1392 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1393 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1394 $item['verb'] = trim(defaults($item, 'verb', ''));
1395 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1396 $item['object'] = trim(defaults($item, 'object', ''));
1397 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1398 $item['target'] = trim(defaults($item, 'target', ''));
1399 $item['plink'] = trim(defaults($item, 'plink', ''));
1400 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1401 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1402 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1403 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1404 $item['private'] = intval(defaults($item, 'private', 0));
1405 $item['body'] = trim(defaults($item, 'body', ''));
1406 $item['tag'] = trim(defaults($item, 'tag', ''));
1407 $item['attach'] = trim(defaults($item, 'attach', ''));
1408 $item['app'] = trim(defaults($item, 'app', ''));
1409 $item['origin'] = intval(defaults($item, 'origin', 0));
1410 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1411 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1412 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1413 $item['inform'] = trim(defaults($item, 'inform', ''));
1414 $item['file'] = trim(defaults($item, 'file', ''));
1416 // When there is no content then we don't post it
1417 if ($item['body'].$item['title'] == '') {
1418 Logger::notice('No body, no title.');
1422 self::addLanguageToItemArray($item);
1424 // Items cannot be stored before they happen ...
1425 if ($item['created'] > DateTimeFormat::utcNow()) {
1426 $item['created'] = DateTimeFormat::utcNow();
1429 // We haven't invented time travel by now.
1430 if ($item['edited'] > DateTimeFormat::utcNow()) {
1431 $item['edited'] = DateTimeFormat::utcNow();
1434 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1436 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1437 $item["contact-id"] = self::contactId($item);
1439 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1440 'photo' => $item['author-avatar'], 'network' => $item['network']];
1442 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1444 if (Contact::isBlocked($item["author-id"])) {
1445 Logger::notice('Author is blocked node-wide', ['author-link' => $item["author-link"], 'item-uri' => $item["uri"]]);
1449 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1450 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1452 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1454 if (Contact::isBlocked($item["owner-id"])) {
1455 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item["owner-link"], 'item-uri' => $item["uri"]]);
1459 if ($item['network'] == Protocol::PHANTOM) {
1460 $item['network'] = Protocol::DFRN;
1461 Logger::notice('Missing network, setting to {network}.', [
1462 'uri' => $item["uri"],
1463 'network' => $item['network'],
1464 'callstack' => System::callstack()
1468 // Checking if there is already an item with the same guid
1469 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1470 if (self::exists($condition)) {
1471 Logger::notice('Found already existing item', [
1472 'guid' => $item['guid'],
1473 'uid' => $item['uid'],
1474 'network' => $item['network']
1479 if ($item['verb'] == ACTIVITY_FOLLOW) {
1480 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1481 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1482 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1486 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => $item['uid'],
1487 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1488 if (self::exists($condition)) {
1489 // It happens that we receive multiple follow requests by the same author - we only store one.
1490 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1495 // Check for hashtags in the body and repair or add hashtag links
1496 self::setHashtags($item);
1498 $item['thr-parent'] = $item['parent-uri'];
1506 if ($item['parent-uri'] === $item['uri']) {
1508 $parent_deleted = 0;
1509 $allow_cid = $item['allow_cid'];
1510 $allow_gid = $item['allow_gid'];
1511 $deny_cid = $item['deny_cid'];
1512 $deny_gid = $item['deny_gid'];
1513 $notify_type = 'wall-new';
1515 // find the parent and snarf the item id and ACLs
1516 // and anything else we need to inherit
1518 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1519 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1520 'wall', 'private', 'forum_mode', 'origin'];
1521 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1522 $params = ['order' => ['id' => false]];
1523 $parent = self::selectFirst($fields, $condition, $params);
1525 if (DBA::isResult($parent)) {
1526 // is the new message multi-level threaded?
1527 // even though we don't support it now, preserve the info
1528 // and re-attach to the conversation parent.
1530 if ($parent['uri'] != $parent['parent-uri']) {
1531 $item['parent-uri'] = $parent['parent-uri'];
1533 $condition = ['uri' => $item['parent-uri'],
1534 'parent-uri' => $item['parent-uri'],
1535 'uid' => $item['uid']];
1536 $params = ['order' => ['id' => false]];
1537 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1539 if (DBA::isResult($toplevel_parent)) {
1540 $parent = $toplevel_parent;
1544 $parent_id = $parent['id'];
1545 $parent_deleted = $parent['deleted'];
1546 $allow_cid = $parent['allow_cid'];
1547 $allow_gid = $parent['allow_gid'];
1548 $deny_cid = $parent['deny_cid'];
1549 $deny_gid = $parent['deny_gid'];
1550 $item['wall'] = $parent['wall'];
1551 $notify_type = 'comment-new';
1554 * If the parent is private, force privacy for the entire conversation
1555 * This differs from the above settings as it subtly allows comments from
1556 * email correspondents to be private even if the overall thread is not.
1558 if ($parent['private']) {
1559 $item['private'] = $parent['private'];
1563 * Edge case. We host a public forum that was originally posted to privately.
1564 * The original author commented, but as this is a comment, the permissions
1565 * weren't fixed up so it will still show the comment as private unless we fix it here.
1567 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1568 $item['private'] = 0;
1571 // If its a post that originated here then tag the thread as "mention"
1572 if ($item['origin'] && $item['uid']) {
1573 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1574 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1578 * Allow one to see reply tweets from status.net even when
1579 * we don't have or can't see the original post.
1581 if ($force_parent) {
1582 Logger::log('$force_parent=true, reply converted to top-level post.');
1584 $item['parent-uri'] = $item['uri'];
1585 $item['gravity'] = GRAVITY_PARENT;
1587 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1591 $parent_deleted = 0;
1595 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1596 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1598 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1599 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1600 if (self::exists($condition)) {
1601 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1605 // On Friendica and Diaspora the GUID is unique
1606 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1607 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1608 if (self::exists($condition)) {
1609 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1613 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1614 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1615 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1616 if (self::exists($condition)) {
1617 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1622 // Is this item available in the global items (with uid=0)?
1623 if ($item["uid"] == 0) {
1624 $item["global"] = true;
1626 // Set the global flag on all items if this was a global item entry
1627 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1629 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1633 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1636 $private = $item['private'];
1639 $item["allow_cid"] = $allow_cid;
1640 $item["allow_gid"] = $allow_gid;
1641 $item["deny_cid"] = $deny_cid;
1642 $item["deny_gid"] = $deny_gid;
1643 $item["private"] = $private;
1644 $item["deleted"] = $parent_deleted;
1646 // Fill the cache field
1647 self::putInCache($item);
1650 $item['edit'] = false;
1651 $item['parent'] = $parent_id;
1652 Hook::callAll('post_local', $item);
1653 unset($item['edit']);
1654 unset($item['parent']);
1656 Hook::callAll('post_remote', $item);
1659 // This array field is used to trigger some automatic reactions
1660 // It is mainly used in the "post_local" hook.
1661 unset($item['api_source']);
1663 if (!empty($item['cancel'])) {
1664 Logger::log('post cancelled by addon.');
1669 * Check for already added items.
1670 * There is a timing issue here that sometimes creates double postings.
1671 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1673 if ($item["uid"] == 0) {
1674 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1675 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1680 Logger::log('' . print_r($item,true), Logger::DATA);
1682 if (array_key_exists('tag', $item)) {
1683 $tags = $item['tag'];
1684 unset($item['tag']);
1689 if (array_key_exists('file', $item)) {
1690 $files = $item['file'];
1691 unset($item['file']);
1696 // Creates or assigns the permission set
1697 $item['psid'] = PermissionSet::fetchIDForPost($item);
1699 // We are doing this outside of the transaction to avoid timing problems
1700 if (!self::insertActivity($item)) {
1701 self::insertContent($item);
1704 $delivery_data = ItemDeliveryData::extractFields($item);
1706 unset($item['postopts']);
1707 unset($item['inform']);
1709 // These fields aren't stored anymore in the item table, they are fetched upon request
1710 unset($item['author-link']);
1711 unset($item['author-name']);
1712 unset($item['author-avatar']);
1714 unset($item['owner-link']);
1715 unset($item['owner-name']);
1716 unset($item['owner-avatar']);
1719 $ret = DBA::insert('item', $item);
1721 // When the item was successfully stored we fetch the ID of the item.
1722 if (DBA::isResult($ret)) {
1723 $current_post = DBA::lastInsertId();
1725 // This can happen - for example - if there are locking timeouts.
1728 // Store the data into a spool file so that we can try again later.
1730 // At first we restore the Diaspora signature that we removed above.
1731 if (isset($encoded_signature)) {
1732 $item['dsprsig'] = $encoded_signature;
1735 // Now we store the data in the spool directory
1736 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1737 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1739 $spoolpath = get_spoolpath();
1740 if ($spoolpath != "") {
1741 $spool = $spoolpath.'/'.$file;
1743 file_put_contents($spool, json_encode($orig_item));
1744 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1749 if ($current_post == 0) {
1750 // This is one of these error messages that never should occur.
1751 Logger::log("couldn't find created item - we better quit now.");
1756 // How much entries have we created?
1757 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1758 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1761 // There are duplicates. We delete our just created entry.
1762 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1764 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1765 DBA::delete('item', ['id' => $current_post]);
1768 } elseif ($entries == 0) {
1769 // This really should never happen since we quit earlier if there were problems.
1770 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1775 Logger::log('created item '.$current_post);
1776 self::updateContact($item);
1778 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1779 $parent_id = $current_post;
1783 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1785 $item['id'] = $current_post;
1786 $item['parent'] = $parent_id;
1788 // update the commented timestamp on the parent
1789 // Only update "commented" if it is really a comment
1790 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1791 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1793 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1798 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1799 * We can check for this condition when we decode and encode the stuff again.
1801 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1802 $dsprsig->signature = base64_decode($dsprsig->signature);
1803 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1806 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1807 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1809 // The other fields are used by very old Friendica servers, so we currently store them differently
1810 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1811 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1815 if (!empty($diaspora_signed_text)) {
1816 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1819 self::tagDeliver($item['uid'], $current_post);
1822 * current post can be deleted if is for a community page and no mention are
1826 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1827 if (DBA::isResult($posted_item)) {
1829 Hook::callAll('post_local_end', $posted_item);
1831 Hook::callAll('post_remote_end', $posted_item);
1834 Logger::log('new item not found in DB, id ' . $current_post);
1838 if ($item['parent-uri'] === $item['uri']) {
1839 self::addThread($current_post);
1841 self::updateThread($parent_id);
1844 ItemDeliveryData::insert($current_post, $delivery_data);
1849 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1850 * This is not perfect - but a workable solution until we found the reason for the problem.
1852 if (!empty($tags)) {
1853 Term::insertFromTagFieldByItemId($current_post, $tags);
1856 if (!empty($files)) {
1857 Term::insertFromFileFieldByItemId($current_post, $files);
1860 if ($item['parent-uri'] === $item['uri']) {
1861 self::addShadow($current_post);
1863 self::addShadowPost($current_post);
1866 check_user_notification($current_post);
1869 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1870 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1871 if ($item['gravity'] == GRAVITY_ACTIVITY) {
1872 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1873 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1874 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1879 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1882 return $current_post;
1886 * @brief Insert a new item content entry
1888 * @param array $item The item fields that are to be inserted
1890 * @throws \Exception
1892 private static function insertActivity(&$item)
1894 $activity_index = self::activityToIndex($item['verb']);
1896 if ($activity_index < 0) {
1900 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1902 // We just remove everything that is content
1903 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1904 unset($item[$field]);
1907 // To avoid timing problems, we are using locks.
1908 $locked = Lock::acquire('item_insert_activity');
1910 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1913 // Do we already have this content?
1914 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1915 if (DBA::isResult($item_activity)) {
1916 $item['iaid'] = $item_activity['id'];
1917 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1918 } elseif (DBA::insert('item-activity', $fields)) {
1919 $item['iaid'] = DBA::lastInsertId();
1920 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1922 // This shouldn't happen.
1923 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1924 Lock::release('item_insert_activity');
1928 Lock::release('item_insert_activity');
1934 * @brief Insert a new item content entry
1936 * @param array $item The item fields that are to be inserted
1937 * @throws \Exception
1939 private static function insertContent(&$item)
1941 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1943 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1944 if (isset($item[$field])) {
1945 $fields[$field] = $item[$field];
1946 unset($item[$field]);
1950 // To avoid timing problems, we are using locks.
1951 $locked = Lock::acquire('item_insert_content');
1953 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1956 // Do we already have this content?
1957 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1958 if (DBA::isResult($item_content)) {
1959 $item['icid'] = $item_content['id'];
1960 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1961 } elseif (DBA::insert('item-content', $fields)) {
1962 $item['icid'] = DBA::lastInsertId();
1963 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1965 // This shouldn't happen.
1966 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1969 Lock::release('item_insert_content');
1974 * @brief Update existing item content entries
1976 * @param array $item The item fields that are to be changed
1977 * @param array $condition The condition for finding the item content entries
1979 * @throws \Exception
1981 private static function updateActivity($item, $condition)
1983 if (empty($item['verb'])) {
1986 $activity_index = self::activityToIndex($item['verb']);
1988 if ($activity_index < 0) {
1992 $fields = ['activity' => $activity_index];
1994 Logger::log('Update activity for ' . json_encode($condition));
1996 DBA::update('item-activity', $fields, $condition, true);
2002 * @brief Update existing item content entries
2004 * @param array $item The item fields that are to be changed
2005 * @param array $condition The condition for finding the item content entries
2006 * @throws \Exception
2008 private static function updateContent($item, $condition)
2010 // We have to select only the fields from the "item-content" table
2012 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2013 if (isset($item[$field])) {
2014 $fields[$field] = $item[$field];
2018 if (empty($fields)) {
2019 // when there are no fields at all, just use the condition
2020 // This is to ensure that we always store content.
2021 $fields = $condition;
2024 Logger::log('Update content for ' . json_encode($condition));
2026 DBA::update('item-content', $fields, $condition, true);
2030 * @brief Distributes public items to the receivers
2032 * @param integer $itemid Item ID that should be added
2033 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2034 * @throws \Exception
2036 public static function distribute($itemid, $signed_text = '')
2038 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2039 $parent = self::selectFirst(['owner-id'], $condition);
2040 if (!DBA::isResult($parent)) {
2044 // Only distribute public items from native networks
2045 $condition = ['id' => $itemid, 'uid' => 0,
2046 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2047 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2048 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2049 if (!DBA::isResult($item)) {
2053 $origin = $item['origin'];
2056 unset($item['parent']);
2057 unset($item['mention']);
2058 unset($item['wall']);
2059 unset($item['origin']);
2060 unset($item['starred']);
2064 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2065 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2066 if (!DBA::isResult($owner)) {
2070 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2071 $contacts = DBA::select('contact', ['uid'], $condition);
2072 while ($contact = DBA::fetch($contacts)) {
2073 if ($contact['uid'] == 0) {
2077 $users[$contact['uid']] = $contact['uid'];
2079 DBA::close($contacts);
2081 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2082 $contacts = DBA::select('contact', ['uid'], $condition);
2083 while ($contact = DBA::fetch($contacts)) {
2084 if ($contact['uid'] == 0) {
2088 $users[$contact['uid']] = $contact['uid'];
2090 DBA::close($contacts);
2092 if (!empty($owner['alias'])) {
2093 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2094 $contacts = DBA::select('contact', ['uid'], $condition);
2095 while ($contact = DBA::fetch($contacts)) {
2096 if ($contact['uid'] == 0) {
2100 $users[$contact['uid']] = $contact['uid'];
2102 DBA::close($contacts);
2107 if ($item['uri'] != $item['parent-uri']) {
2108 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2109 while ($parent = self::fetch($parents)) {
2110 $users[$parent['uid']] = $parent['uid'];
2111 if ($parent['origin'] && !$origin) {
2112 $origin_uid = $parent['uid'];
2117 foreach ($users as $uid) {
2118 if ($origin_uid == $uid) {
2119 $item['diaspora_signed_text'] = $signed_text;
2121 self::storeForUser($itemid, $item, $uid);
2126 * @brief Store public items for the receivers
2128 * @param integer $itemid Item ID that should be added
2129 * @param array $item The item entry that will be stored
2130 * @param integer $uid The user that will receive the item entry
2131 * @throws \Exception
2133 private static function storeForUser($itemid, $item, $uid)
2135 $item['uid'] = $uid;
2136 $item['origin'] = 0;
2138 if ($item['uri'] == $item['parent-uri']) {
2139 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2141 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2144 if (empty($item['contact-id'])) {
2145 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2146 if (!DBA::isResult($self)) {
2149 $item['contact-id'] = $self['id'];
2152 /// @todo Handling of "event-id"
2155 if ($item['uri'] == $item['parent-uri']) {
2156 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2157 if (DBA::isResult($contact)) {
2158 $notify = self::isRemoteSelf($contact, $item);
2162 $distributed = self::insert($item, false, $notify, true);
2164 if (!$distributed) {
2165 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2167 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2172 * @brief Add a shadow entry for a given item id that is a thread starter
2174 * We store every public item entry additionally with the user id "0".
2175 * This is used for the community page and for the search.
2176 * It is planned that in the future we will store public item entries only once.
2178 * @param integer $itemid Item ID that should be added
2179 * @throws \Exception
2181 public static function addShadow($itemid)
2183 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2184 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2185 $item = self::selectFirst($fields, $condition);
2187 if (!DBA::isResult($item)) {
2191 // is it already a copy?
2192 if (($itemid == 0) || ($item['uid'] == 0)) {
2196 // Is it a visible public post?
2197 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2201 // is it an entry from a connector? Only add an entry for natively connected networks
2202 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2206 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2210 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2212 if (DBA::isResult($item)) {
2213 // Preparing public shadow (removing user specific data)
2216 unset($item['parent']);
2217 unset($item['wall']);
2218 unset($item['mention']);
2219 unset($item['origin']);
2220 unset($item['starred']);
2221 unset($item['postopts']);
2222 unset($item['inform']);
2223 if ($item['uri'] == $item['parent-uri']) {
2224 $item['contact-id'] = $item['owner-id'];
2226 $item['contact-id'] = $item['author-id'];
2229 $public_shadow = self::insert($item, false, false, true);
2231 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2236 * @brief Add a shadow entry for a given item id that is a comment
2238 * This function does the same like the function above - but for comments
2240 * @param integer $itemid Item ID that should be added
2241 * @throws \Exception
2243 public static function addShadowPost($itemid)
2245 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2246 if (!DBA::isResult($item)) {
2250 // Is it a toplevel post?
2251 if ($item['id'] == $item['parent']) {
2252 self::addShadow($itemid);
2256 // Is this a shadow entry?
2257 if ($item['uid'] == 0) {
2261 // Is there a shadow parent?
2262 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2266 // Is there already a shadow entry?
2267 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2271 // Save "origin" and "parent" state
2272 $origin = $item['origin'];
2273 $parent = $item['parent'];
2275 // Preparing public shadow (removing user specific data)
2278 unset($item['parent']);
2279 unset($item['wall']);
2280 unset($item['mention']);
2281 unset($item['origin']);
2282 unset($item['starred']);
2283 unset($item['postopts']);
2284 unset($item['inform']);
2285 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2287 $public_shadow = self::insert($item, false, false, true);
2289 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2291 // If this was a comment to a Diaspora post we don't get our comment back.
2292 // This means that we have to distribute the comment by ourselves.
2293 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2294 self::distribute($public_shadow);
2299 * Adds a language specification in a "language" element of given $arr.
2300 * Expects "body" element to exist in $arr.
2303 * @throws \Text_LanguageDetect_Exception
2305 private static function addLanguageToItemArray(&$item)
2307 $naked_body = BBCode::toPlaintext($item['body'], false);
2309 $ld = new Text_LanguageDetect();
2310 $ld->setNameMode(2);
2311 $languages = $ld->detect($naked_body, 3);
2313 if (is_array($languages)) {
2314 $item['language'] = json_encode($languages);
2319 * @brief Creates an unique guid out of a given uri
2321 * @param string $uri uri of an item entry
2322 * @param string $host hostname for the GUID prefix
2323 * @return string unique guid
2325 public static function guidFromUri($uri, $host)
2327 // Our regular guid routine is using this kind of prefix as well
2328 // We have to avoid that different routines could accidentally create the same value
2329 $parsed = parse_url($uri);
2331 // We use a hash of the hostname as prefix for the guid
2332 $guid_prefix = hash("crc32", $host);
2334 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2335 unset($parsed["scheme"]);
2337 // Glue it together to be able to make a hash from it
2338 $host_id = implode("/", $parsed);
2340 // We could use any hash algorithm since it isn't a security issue
2341 $host_hash = hash("ripemd128", $host_id);
2343 return $guid_prefix.$host_hash;
2347 * generate an unique URI
2349 * @param integer $uid User id
2350 * @param string $guid An existing GUID (Otherwise it will be generated)
2353 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2355 public static function newURI($uid, $guid = "")
2358 $guid = System::createUUID();
2361 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2365 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2367 * This can be used to filter for inactive contacts.
2368 * Only do this for public postings to avoid privacy problems, since poco data is public.
2369 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2371 * @param array $arr Contains the just posted item record
2372 * @throws \Exception
2374 private static function updateContact($arr)
2376 // Unarchive the author
2377 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2378 if (DBA::isResult($contact)) {
2379 Contact::unmarkForArchival($contact);
2382 // Unarchive the contact if it's not our own contact
2383 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2384 if (DBA::isResult($contact)) {
2385 Contact::unmarkForArchival($contact);
2388 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2390 // Is it a forum? Then we don't care about the rules from above
2391 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2392 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2398 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2399 ['id' => $arr['contact-id']]);
2401 // Now do the same for the system wide contacts with uid=0
2402 if (!$arr['private']) {
2403 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2404 ['id' => $arr['owner-id']]);
2406 if ($arr['owner-id'] != $arr['author-id']) {
2407 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2408 ['id' => $arr['author-id']]);
2413 public static function setHashtags(&$item)
2415 $tags = BBCode::getTags($item["body"]);
2418 if (!count($tags)) {
2422 // What happens in [code], stays in [code]!
2423 // escape the # and the [
2424 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2425 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2427 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2429 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2430 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2433 // This sorting is important when there are hashtags that are part of other hashtags
2434 // Otherwise there could be problems with hashtags like #test and #test2
2437 $URLSearchString = "^\[\]";
2439 // All hashtags should point to the home server if "local_tags" is activated
2440 if (Config::get('system', 'local_tags')) {
2441 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2442 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2444 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2445 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2448 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2449 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2451 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2454 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2456 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2459 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2461 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2464 // Repair recursive urls
2465 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2466 "#$2", $item["body"]);
2468 foreach ($tags as $tag) {
2469 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
2473 $basetag = str_replace('_',' ',substr($tag,1));
2474 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2476 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2478 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2479 if (strlen($item["tag"])) {
2480 $item["tag"] = ',' . $item["tag"];
2482 $item["tag"] = $newtag . $item["tag"];
2486 // Convert back the masked hashtags
2487 $item["body"] = str_replace("#", "#", $item["body"]);
2489 // Remember! What happens in [code], stays in [code]
2490 // roleback the # and [
2491 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2493 // we truly unESCape all sharp and leftsquarebracket
2494 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2495 $replace = ['#', '['];
2496 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
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
2513 * @param string $guid item guid
2514 * @param int $uid user id
2515 * @return array with id and nick of the item with the given guid
2516 * @throws \Exception
2518 public static function getIdAndNickByGuid($guid, $uid = 0)
2524 $uid = local_user();
2527 // Does the given user have this item?
2529 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2530 if (DBA::isResult($item)) {
2531 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2532 if (!DBA::isResult($user)) {
2536 $nick = $user['nickname'];
2540 // Or is it anywhere on the server?
2542 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2543 $item = self::selectFirst(['id', 'uid'], $condition);
2544 if (DBA::isResult($item)) {
2545 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2546 if (!DBA::isResult($user)) {
2550 $nick = $user['nickname'];
2553 return ["nick" => $nick, "id" => $id];
2557 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2560 * @param int $item_id
2561 * @return void true if item was deleted, else false
2562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2563 * @throws \ImagickException
2565 private static function tagDeliver($uid, $item_id)
2569 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2570 if (!DBA::isResult($user)) {
2574 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2575 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2577 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2578 if (!DBA::isResult($item)) {
2582 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2585 * Diaspora uses their own hardwired link URL in @-tags
2586 * instead of the one we supply with webfinger
2588 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2590 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2592 foreach ($matches as $mtch) {
2593 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2595 Logger::log('mention found: ' . $mtch[2]);
2601 if (($community_page || $prvgroup) &&
2602 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2603 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2605 Logger::log("no-mention top-level post to community or private group. delete.");
2606 DBA::delete('item', ['id' => $item_id]);
2612 $arr = ['item' => $item, 'user' => $user];
2614 Hook::callAll('tagged', $arr);
2616 if (!$community_page && !$prvgroup) {
2621 * tgroup delivery - setup a second delivery chain
2622 * prevent delivery looping - only proceed
2623 * if the message originated elsewhere and is a top-level post
2625 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2629 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2630 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2631 if (!DBA::isResult($self)) {
2635 $owner_id = Contact::getIdForURL($self['url']);
2637 // also reset all the privacy bits to the forum default permissions
2639 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2641 $psid = PermissionSet::fetchIDForPost($user);
2643 $forum_mode = ($prvgroup ? 2 : 1);
2645 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2646 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2647 self::update($fields, ['id' => $item_id]);
2649 self::updateThread($item_id);
2651 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2654 public static function isRemoteSelf($contact, &$datarray)
2658 if (!$contact['remote_self']) {
2662 // Prevent the forwarding of posts that are forwarded
2663 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2664 Logger::log('Already forwarded', Logger::DEBUG);
2668 // Prevent to forward already forwarded posts
2669 if ($datarray["app"] == $a->getHostName()) {
2670 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2674 // Only forward posts
2675 if ($datarray["verb"] != ACTIVITY_POST) {
2676 Logger::log('No post', Logger::DEBUG);
2680 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2681 Logger::log('Not public', Logger::DEBUG);
2685 $datarray2 = $datarray;
2686 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2687 if ($contact['remote_self'] == 2) {
2688 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2689 ['uid' => $contact['uid'], 'self' => true]);
2690 if (DBA::isResult($self)) {
2691 $datarray['contact-id'] = $self["id"];
2693 $datarray['owner-name'] = $self["name"];
2694 $datarray['owner-link'] = $self["url"];
2695 $datarray['owner-avatar'] = $self["thumb"];
2697 $datarray['author-name'] = $datarray['owner-name'];
2698 $datarray['author-link'] = $datarray['owner-link'];
2699 $datarray['author-avatar'] = $datarray['owner-avatar'];
2701 unset($datarray['created']);
2702 unset($datarray['edited']);
2704 unset($datarray['network']);
2705 unset($datarray['owner-id']);
2706 unset($datarray['author-id']);
2709 if ($contact['network'] != Protocol::FEED) {
2710 $datarray["guid"] = System::createUUID();
2711 unset($datarray["plink"]);
2712 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2713 $datarray["parent-uri"] = $datarray["uri"];
2714 $datarray["thr-parent"] = $datarray["uri"];
2715 $datarray["extid"] = Protocol::DFRN;
2716 $urlpart = parse_url($datarray2['author-link']);
2717 $datarray["app"] = $urlpart["host"];
2719 $datarray['private'] = 0;
2723 if ($contact['network'] != Protocol::FEED) {
2724 // Store the original post
2725 $result = self::insert($datarray2, false, false);
2726 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2728 $datarray["app"] = "Feed";
2732 // Trigger automatic reactions for addons
2733 $datarray['api_source'] = true;
2735 // We have to tell the hooks who we are - this really should be improved
2736 $_SESSION["authenticated"] = true;
2737 $_SESSION["uid"] = $contact['uid'];
2746 * @param array $item
2749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2750 * @throws \ImagickException
2752 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2754 if (Config::get('system', 'disable_embedded')) {
2758 Logger::log('check for photos', Logger::DEBUG);
2759 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2764 $img_start = strpos($orig_body, '[img');
2765 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2766 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2768 while (($img_st_close !== false) && ($img_len !== false)) {
2769 $img_st_close++; // make it point to AFTER the closing bracket
2770 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2772 Logger::log('found photo ' . $image, Logger::DEBUG);
2774 if (stristr($image, $site . '/photo/')) {
2775 // Only embed locally hosted photos
2777 $i = basename($image);
2778 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2779 $x = strpos($i, '-');
2782 $res = substr($i, $x + 1);
2783 $i = substr($i, 0, $x);
2784 $photo = Photo::getPhotoForUser($uid, $i, $res);
2785 if (DBA::isResult($photo)) {
2787 * Check to see if we should replace this photo link with an embedded image
2788 * 1. No need to do so if the photo is public
2789 * 2. If there's a contact-id provided, see if they're in the access list
2790 * for the photo. If so, embed it.
2791 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2792 * permissions, regardless of order but first check to see if they're an exact
2793 * match to save some processing overhead.
2795 if (self::hasPermissions($photo)) {
2797 $recips = self::enumeratePermissions($photo);
2798 if (in_array($cid, $recips)) {
2802 if (self::samePermissions($item, $photo)) {
2808 $photo_img = Photo::getImageForPhoto($photo);
2809 // If a custom width and height were specified, apply before embedding
2810 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2811 Logger::log('scaling photo', Logger::DEBUG);
2813 $width = intval($match[1]);
2814 $height = intval($match[2]);
2816 $photo_img->scaleDown(max($width, $height));
2819 $data = $photo_img->asString();
2820 $type = $photo_img->getType();
2822 Logger::log('replacing photo', Logger::DEBUG);
2823 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2824 Logger::log('replaced: ' . $image, Logger::DATA);
2830 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2831 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2832 if ($orig_body === false) {
2836 $img_start = strpos($orig_body, '[img');
2837 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2838 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2841 $new_body = $new_body . $orig_body;
2846 private static function hasPermissions($obj)
2848 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2849 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2852 private static function samePermissions($obj1, $obj2)
2854 // first part is easy. Check that these are exactly the same.
2855 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2856 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2857 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2858 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2862 // This is harder. Parse all the permissions and compare the resulting set.
2863 $recipients1 = self::enumeratePermissions($obj1);
2864 $recipients2 = self::enumeratePermissions($obj2);
2868 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2869 return ($recipients1 == $recipients2);
2872 // returns an array of contact-ids that are allowed to see this object
2873 public static function enumeratePermissions($obj)
2875 $allow_people = expand_acl($obj['allow_cid']);
2876 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2877 $deny_people = expand_acl($obj['deny_cid']);
2878 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2879 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2880 $deny = array_unique(array_merge($deny_people, $deny_groups));
2881 $recipients = array_diff($recipients, $deny);
2885 public static function getFeedTags($item)
2889 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2891 for ($x = 0; $x < $cnt; $x ++) {
2892 if ($matches[1][$x]) {
2893 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2898 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2900 for ($x = 0; $x < $cnt; $x ++) {
2901 if ($matches[1][$x]) {
2902 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2909 public static function expire($uid, $days, $network = "", $force = false)
2911 if (!$uid || ($days < 1)) {
2915 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2916 $uid, GRAVITY_PARENT];
2919 * $expire_network_only = save your own wall posts
2920 * and just expire conversations started by others
2922 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2924 if ($expire_network_only) {
2925 $condition[0] .= " AND NOT `wall`";
2928 if ($network != "") {
2929 $condition[0] .= " AND `network` = ?";
2930 $condition[] = $network;
2933 * There is an index "uid_network_received" but not "uid_network_created"
2934 * This avoids the creation of another index just for one purpose.
2935 * And it doesn't really matter wether to look at "received" or "created"
2937 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2938 $condition[] = $days;
2940 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2941 $condition[] = $days;
2944 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2946 if (!DBA::isResult($items)) {
2950 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2952 // Forcing expiring of items - but not notes and marked items
2954 $expire_items = true;
2957 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2958 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2959 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2963 while ($item = Item::fetch($items)) {
2964 // don't expire filed items
2966 if (strpos($item['file'], '[') !== false) {
2970 // Only expire posts, not photos and photo comments
2972 if (!$expire_photos && strlen($item['resource-id'])) {
2974 } elseif (!$expire_starred && intval($item['starred'])) {
2976 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2978 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2982 self::deleteById($item['id'], PRIORITY_LOW);
2987 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2990 public static function firstPostDate($uid, $wall = false)
2992 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2993 $params = ['order' => ['created' => false]];
2994 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2995 if (DBA::isResult($thread)) {
2996 return substr(DateTimeFormat::local($thread['created']), 0, 10);
3002 * @brief add/remove activity to an item
3004 * Toggle activities as like,dislike,attend of an item
3006 * @param string $item_id
3007 * @param string $verb
3008 * Activity verb. One of
3009 * like, unlike, dislike, undislike, attendyes, unattendyes,
3010 * attendno, unattendno, attendmaybe, unattendmaybe
3012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3013 * @throws \ImagickException
3014 * @hook 'post_local_end'
3016 * 'post_id' => ID of posted item
3018 public static function performLike($item_id, $verb)
3020 if (!local_user() && !remote_user()) {
3027 $activity = ACTIVITY_LIKE;
3031 $activity = ACTIVITY_DISLIKE;
3035 $activity = ACTIVITY_ATTEND;
3039 $activity = ACTIVITY_ATTENDNO;
3042 case 'unattendmaybe':
3043 $activity = ACTIVITY_ATTENDMAYBE;
3046 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3050 // Enable activity toggling instead of on/off
3051 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3053 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3055 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3056 if (!DBA::isResult($item)) {
3057 Logger::log('like: unknown item ' . $item_id);
3061 $item_uri = $item['uri'];
3063 $uid = $item['uid'];
3064 if (($uid == 0) && local_user()) {
3065 $uid = local_user();
3068 if (!Security::canWriteToUserWall($uid)) {
3069 Logger::log('like: unable to write on wall ' . $uid);
3073 // Retrieves the local post owner
3074 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3075 if (!DBA::isResult($owner_self_contact)) {
3076 Logger::log('like: unknown owner ' . $uid);
3080 // Retrieve the current logged in user's public contact
3081 $author_id = public_contact();
3083 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3084 if (!DBA::isResult($author_contact)) {
3085 Logger::log('like: unknown author ' . $author_id);
3089 // Contact-id is the uid-dependant author contact
3090 if (local_user() == $uid) {
3091 $item_contact_id = $owner_self_contact['id'];
3093 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3094 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3095 if (!DBA::isResult($item_contact)) {
3096 Logger::log('like: unknown item contact ' . $item_contact_id);
3101 // Look for an existing verb row
3102 // event participation are essentially radio toggles. If you make a subsequent choice,
3103 // we need to eradicate your first choice.
3104 if ($event_verb_flag) {
3105 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3107 // Translate to the index based activity index
3109 foreach ($verbs as $verb) {
3110 $activities[] = self::activityToIndex($verb);
3113 $activities = self::activityToIndex($activity);
3116 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3117 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3119 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3121 // If it exists, mark it as deleted
3122 if (DBA::isResult($like_item)) {
3123 self::deleteById($like_item['id']);
3125 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3130 // Verb is "un-something", just trying to delete existing entries
3131 if (strpos($verb, 'un') === 0) {
3135 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3138 'guid' => System::createUUID(),
3139 'uri' => self::newURI($item['uid']),
3140 'uid' => $item['uid'],
3141 'contact-id' => $item_contact_id,
3142 'wall' => $item['wall'],
3144 'network' => Protocol::DFRN,
3145 'gravity' => GRAVITY_ACTIVITY,
3146 'parent' => $item['id'],
3147 'parent-uri' => $item['uri'],
3148 'thr-parent' => $item['uri'],
3149 'owner-id' => $author_id,
3150 'author-id' => $author_id,
3151 'body' => $activity,
3152 'verb' => $activity,
3153 'object-type' => $objtype,
3154 'allow_cid' => $item['allow_cid'],
3155 'allow_gid' => $item['allow_gid'],
3156 'deny_cid' => $item['deny_cid'],
3157 'deny_gid' => $item['deny_gid'],
3162 $signed = Diaspora::createLikeSignature($uid, $new_item);
3163 if (!empty($signed)) {
3164 $new_item['diaspora_signed_text'] = json_encode($signed);
3167 $new_item_id = self::insert($new_item);
3169 // If the parent item isn't visible then set it to visible
3170 if (!$item['visible']) {
3171 self::update(['visible' => true], ['id' => $item['id']]);
3174 $new_item['id'] = $new_item_id;
3176 Hook::callAll('post_local_end', $new_item);
3181 private static function addThread($itemid, $onlyshadow = false)
3183 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3184 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3185 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3186 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3187 $item = self::selectFirst($fields, $condition);
3189 if (!DBA::isResult($item)) {
3193 $item['iid'] = $itemid;
3196 $result = DBA::insert('thread', $item);
3198 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3202 private static function updateThread($itemid, $setmention = false)
3204 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3205 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3206 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3207 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3209 $item = self::selectFirst($fields, $condition);
3210 if (!DBA::isResult($item)) {
3215 $item["mention"] = 1;
3220 foreach ($item as $field => $data) {
3221 if (!in_array($field, ["guid"])) {
3222 $fields[$field] = $data;
3226 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3228 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3231 private static function deleteThread($itemid, $itemuri = "")
3233 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3234 if (!DBA::isResult($item)) {
3235 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3239 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3241 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3243 if ($itemuri != "") {
3244 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3245 if (!self::exists($condition)) {
3246 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3247 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3252 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3254 $local_user = local_user();
3255 $remote_user = remote_user();
3258 * Construct permissions
3260 * default permissions - anonymous user
3262 $sql = " AND NOT `item`.`private`";
3264 // Profile owner - everything is visible
3265 if ($local_user && ($local_user == $owner_id)) {
3267 } elseif ($remote_user) {
3269 * Authenticated visitor. Unless pre-verified,
3270 * check that the contact belongs to this $owner_id
3271 * and load the groups the visitor belongs to.
3272 * If pre-verified, the caller is expected to have already
3273 * done this and passed the groups into this function.
3275 $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3278 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3283 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3290 * get translated item type
3295 public static function postType($item)
3297 if (!empty($item['event-id'])) {
3298 return L10n::t('event');
3299 } elseif (!empty($item['resource-id'])) {
3300 return L10n::t('photo');
3301 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3302 return L10n::t('activity');
3303 } elseif ($item['id'] != $item['parent']) {
3304 return L10n::t('comment');
3307 return L10n::t('post');
3311 * Sets the "rendered-html" field of the provided item
3313 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3315 * @param array $item
3316 * @param bool $update
3318 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3319 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3321 public static function putInCache(&$item, $update = false)
3323 $body = $item["body"];
3325 $rendered_hash = defaults($item, 'rendered-hash', '');
3326 $rendered_html = defaults($item, 'rendered-html', '');
3328 if ($rendered_hash == ''
3329 || $rendered_html == ""
3330 || $rendered_hash != hash("md5", $item["body"])
3331 || Config::get("system", "ignore_cache")
3333 $a = self::getApp();
3334 redir_private_images($a, $item);
3336 $item["rendered-html"] = prepare_text($item["body"]);
3337 $item["rendered-hash"] = hash("md5", $item["body"]);
3339 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3340 Hook::callAll('put_item_in_cache', $hook_data);
3341 $item['rendered-html'] = $hook_data['rendered-html'];
3342 $item['rendered-hash'] = $hook_data['rendered-hash'];
3345 // Force an update if the generated values differ from the existing ones
3346 if ($rendered_hash != $item["rendered-hash"]) {
3350 // Only compare the HTML when we forcefully ignore the cache
3351 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3355 if ($update && !empty($item["id"])) {
3358 'rendered-html' => $item["rendered-html"],
3359 'rendered-hash' => $item["rendered-hash"]
3361 ['id' => $item["id"]]
3366 $item["body"] = $body;
3370 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3371 * If attach is true, also add icons for item attachments.
3373 * @param array $item
3374 * @param boolean $attach
3375 * @param boolean $is_preview
3376 * @return string item body html
3377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3378 * @throws \ImagickException
3379 * @hook prepare_body_init item array before any work
3380 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3381 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3382 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3384 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3386 $a = self::getApp();
3387 Hook::callAll('prepare_body_init', $item);
3389 // In order to provide theme developers more possibilities, event items
3390 // are treated differently.
3391 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3392 $ev = Event::getItemHTML($item);
3396 $tags = Term::populateTagsFromItem($item);
3398 $item['tags'] = $tags['tags'];
3399 $item['hashtags'] = $tags['hashtags'];
3400 $item['mentions'] = $tags['mentions'];
3402 // Compile eventual content filter reasons
3403 $filter_reasons = [];
3404 if (!$is_preview && public_contact() != $item['author-id']) {
3405 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3406 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3411 'filter_reasons' => $filter_reasons
3413 Hook::callAll('prepare_body_content_filter', $hook_data);
3414 $filter_reasons = $hook_data['filter_reasons'];
3418 // Update the cached values if there is no "zrl=..." on the links.
3419 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3421 // Or update it if the current viewer is the intented viewer.
3422 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3426 self::putInCache($item, $update);
3427 $s = $item["rendered-html"];
3432 'preview' => $is_preview,
3433 'filter_reasons' => $filter_reasons
3435 Hook::callAll('prepare_body', $hook_data);
3436 $s = $hook_data['html'];
3440 // Replace the blockquotes with quotes that are used in mails.
3441 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3442 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3449 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3450 foreach ($matches as $mtch) {
3453 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3455 if (strpos($mime, 'video') !== false) {
3458 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3459 '$baseurl' => System::baseUrl(),
3463 $url_parts = explode('/', $the_url);
3464 $id = end($url_parts);
3465 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3468 'title' => L10n::t('View Video'),
3475 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3477 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3478 $filesubtype = str_replace('.', '-', $filesubtype);
3481 $filesubtype = 'unkn';
3484 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3485 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3487 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3488 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3492 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3496 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3497 $x = Map::byCoordinates(trim($item['coord']));
3499 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3504 // Look for spoiler.
3505 $spoilersearch = '<blockquote class="spoiler">';
3507 // Remove line breaks before the spoiler.
3508 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3509 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3511 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3512 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3515 while ((strpos($s, $spoilersearch) !== false)) {
3516 $pos = strpos($s, $spoilersearch);
3517 $rnd = Strings::getRandomHex(8);
3518 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3519 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3520 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3523 // Look for quote with author.
3524 $authorsearch = '<blockquote class="author">';
3526 while ((strpos($s, $authorsearch) !== false)) {
3527 $pos = strpos($s, $authorsearch);
3528 $rnd = Strings::getRandomHex(8);
3529 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3530 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3531 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3534 // Replace friendica image url size with theme preference.
3535 if (!empty($a->theme_info['item_image_size'])) {
3536 $ps = $a->theme_info['item_image_size'];
3537 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3540 $s = HTML::applyContentFilter($s, $filter_reasons);
3542 $hook_data = ['item' => $item, 'html' => $s];
3543 Hook::callAll('prepare_body_final', $hook_data);
3545 return $hook_data['html'];
3549 * get private link for item
3551 * @param array $item
3552 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3553 * @throws \Exception
3555 public static function getPlink($item)
3557 $a = self::getApp();
3559 if ($a->user['nickname'] != "") {
3561 'href' => "display/" . $item['guid'],
3562 'orig' => "display/" . $item['guid'],
3563 'title' => L10n::t('View on separate page'),
3564 'orig_title' => L10n::t('view on separate page'),
3567 if (!empty($item['plink'])) {
3568 $ret["href"] = $a->removeBaseURL($item['plink']);
3569 $ret["title"] = L10n::t('link to source');
3572 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3574 'href' => $item['plink'],
3575 'orig' => $item['plink'],
3576 'title' => L10n::t('link to source'),