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 Friendica\Util\Network;
31 use Text_LanguageDetect;
33 class Item extends BaseObject
35 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
42 const PT_DOCUMENT = 19;
44 const PT_PERSONAL_NOTE = 128;
46 // Field list that is used to display the items
47 const DISPLAY_FIELDLIST = [
48 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
49 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
50 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
51 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
52 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
53 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
54 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
55 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
56 'writable', 'self', 'cid', 'alias',
57 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
58 'event-summary', 'event-desc', 'event-location', 'event-type',
59 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
60 'delivery_queue_count', 'delivery_queue_done'
63 // Field list that is used to deliver items via the protocols
64 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
65 'created', 'edited', 'verb', 'object-type', 'object', 'target',
66 'private', 'title', 'body', 'location', 'coord', 'app',
67 'attach', 'tag', 'deleted', 'extid', 'post-type',
68 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
69 'author-id', 'author-link', 'owner-link', 'contact-uid',
70 'signed_text', 'signature', 'signer', 'network'];
72 // Field list for "item-content" table that is mixed with the item table
73 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
74 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
75 'object-type', 'object', 'target-type', 'target', 'plink'];
77 // Field list for "item-content" table that is not present in the "item" table
78 const CONTENT_FIELDLIST = ['language'];
80 // All fields in the item table
81 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
82 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
83 'created', 'edited', 'commented', 'received', 'changed', 'verb',
84 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
85 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
86 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
87 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
88 'title', 'content-warning', 'body', 'location', 'coord', 'app',
89 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
90 'author-id', 'author-link', 'author-name', 'author-avatar',
91 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
93 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
94 // The item-activity table only stores the index and needs this array to know the matching activity.
95 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE];
97 private static $legacy_mode = null;
99 public static function isLegacyMode()
101 if (is_null(self::$legacy_mode)) {
102 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
105 return self::$legacy_mode;
109 * @brief returns an activity index from an activity string
111 * @param string $activity activity string
112 * @return integer Activity index
114 public static function activityToIndex($activity)
116 $index = array_search($activity, self::ACTIVITIES);
118 if (is_bool($index)) {
126 * @brief returns an activity string from an activity index
128 * @param integer $index activity index
129 * @return string Activity string
131 private static function indexToActivity($index)
133 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
137 return self::ACTIVITIES[$index];
141 * @brief Fetch a single item row
143 * @param mixed $stmt statement object
144 * @return array current row
146 public static function fetch($stmt)
148 $row = DBA::fetch($stmt);
154 // ---------------------- Transform item structure data ----------------------
156 // We prefer the data from the user's contact over the public one
157 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
158 ($row['author-link'] == $row['contact-link'])) {
159 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
160 $row['author-avatar'] = $row['contact-avatar'];
162 if (isset($row['author-name']) && !empty($row['contact-name'])) {
163 $row['author-name'] = $row['contact-name'];
167 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
168 ($row['owner-link'] == $row['contact-link'])) {
169 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
170 $row['owner-avatar'] = $row['contact-avatar'];
172 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
173 $row['owner-name'] = $row['contact-name'];
177 // We can always comment on posts from these networks
178 if (array_key_exists('writable', $row) &&
179 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
180 $row['writable'] = true;
183 // ---------------------- Transform item content data ----------------------
185 // Fetch data from the item-content table whenever there is content there
186 if (self::isLegacyMode()) {
187 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
188 foreach ($legacy_fields as $field) {
189 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
190 $row[$field] = $row['internal-item-' . $field];
192 unset($row['internal-item-' . $field]);
196 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
197 $row['verb'] = self::indexToActivity($row['internal-activity']);
198 if (array_key_exists('title', $row)) {
201 if (array_key_exists('body', $row)) {
202 $row['body'] = $row['verb'];
204 if (array_key_exists('object', $row)) {
207 if (array_key_exists('object-type', $row)) {
208 $row['object-type'] = ACTIVITY_OBJ_NOTE;
210 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
211 // Posts don't have an object or target - but having tags or files.
212 // We safe some performance by building tag and file strings only here.
213 // We remove object and target since they aren't used for this type.
214 if (array_key_exists('object', $row)) {
217 if (array_key_exists('target', $row)) {
222 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
223 // Build the tag string out of the term entries
224 if (array_key_exists('tag', $row) && empty($row['tag'])) {
225 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
228 // Build the file string out of the term entries
229 if (array_key_exists('file', $row) && empty($row['file'])) {
230 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
234 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
235 $row['signed_text'] = $row['interaction'];
238 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
239 $row['ignored'] = $row['internal-user-ignored'];
242 // Remove internal fields
243 unset($row['internal-activity']);
244 unset($row['internal-network']);
245 unset($row['internal-iid']);
246 unset($row['internal-iaid']);
247 unset($row['internal-icid']);
248 unset($row['internal-user-ignored']);
249 unset($row['interaction']);
255 * @brief Fills an array with data from an item query
257 * @param object $stmt statement object
258 * @param bool $do_close
259 * @return array Data array
261 public static function inArray($stmt, $do_close = true) {
262 if (is_bool($stmt)) {
267 while ($row = self::fetch($stmt)) {
277 * @brief Check if item data exists
279 * @param array $condition array of fields for condition
281 * @return boolean Are there rows for that condition?
284 public static function exists($condition) {
285 $stmt = self::select(['id'], $condition, ['limit' => 1]);
287 if (is_bool($stmt)) {
290 $retval = (DBA::numRows($stmt) > 0);
299 * Retrieve a single record from the item table for a given user and returns it in an associative array
301 * @brief Retrieve a single record from a table
302 * @param integer $uid User ID
303 * @param array $selected
304 * @param array $condition
305 * @param array $params
310 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
312 $params['uid'] = $uid;
314 if (empty($selected)) {
315 $selected = Item::DISPLAY_FIELDLIST;
318 return self::selectFirst($selected, $condition, $params);
322 * @brief Select rows from the item table for a given user
324 * @param integer $uid User ID
325 * @param array $selected Array of selected fields, empty for all
326 * @param array $condition Array of fields for condition
327 * @param array $params Array of several parameters
329 * @return boolean|object
332 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
334 $params['uid'] = $uid;
336 if (empty($selected)) {
337 $selected = Item::DISPLAY_FIELDLIST;
340 return self::select($selected, $condition, $params);
344 * Retrieve a single record from the item table and returns it in an associative array
346 * @brief Retrieve a single record from a table
347 * @param array $fields
348 * @param array $condition
349 * @param array $params
354 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
356 $params['limit'] = 1;
358 $result = self::select($fields, $condition, $params);
360 if (is_bool($result)) {
363 $row = self::fetch($result);
370 * @brief Select rows from the item table
372 * @param array $selected Array of selected fields, empty for all
373 * @param array $condition Array of fields for condition
374 * @param array $params Array of several parameters
376 * @return boolean|object
379 public static function select(array $selected = [], array $condition = [], $params = [])
384 if (isset($params['uid'])) {
385 $uid = $params['uid'];
389 $fields = self::fieldlist($usermode);
391 $select_fields = self::constructSelectFields($fields, $selected);
393 $condition_string = DBA::buildCondition($condition);
395 $condition_string = self::addTablesToFields($condition_string, $fields);
398 $condition_string = $condition_string . ' AND ' . self::condition(false);
401 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
403 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
405 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
407 return DBA::p($sql, $condition);
411 * @brief Select rows from the starting post in the item table
413 * @param integer $uid User ID
414 * @param array $selected
415 * @param array $condition Array of fields for condition
416 * @param array $params Array of several parameters
418 * @return boolean|object
421 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
423 $params['uid'] = $uid;
425 if (empty($selected)) {
426 $selected = Item::DISPLAY_FIELDLIST;
429 return self::selectThread($selected, $condition, $params);
433 * Retrieve a single record from the starting post in the item table and returns it in an associative array
435 * @brief Retrieve a single record from a table
436 * @param integer $uid User ID
437 * @param array $selected
438 * @param array $condition
439 * @param array $params
444 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
446 $params['uid'] = $uid;
448 if (empty($selected)) {
449 $selected = Item::DISPLAY_FIELDLIST;
452 return self::selectFirstThread($selected, $condition, $params);
456 * Retrieve a single record from the starting post in the item table and returns it in an associative array
458 * @brief Retrieve a single record from a table
459 * @param array $fields
460 * @param array $condition
461 * @param array $params
466 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
468 $params['limit'] = 1;
469 $result = self::selectThread($fields, $condition, $params);
471 if (is_bool($result)) {
474 $row = self::fetch($result);
481 * @brief Select rows from the starting post in the item table
483 * @param array $selected Array of selected fields, empty for all
484 * @param array $condition Array of fields for condition
485 * @param array $params Array of several parameters
487 * @return boolean|object
490 public static function selectThread(array $selected = [], array $condition = [], $params = [])
495 if (isset($params['uid'])) {
496 $uid = $params['uid'];
500 $fields = self::fieldlist($usermode);
502 $fields['thread'] = ['mention', 'ignored', 'iid'];
504 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
505 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
506 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
507 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
509 $select_fields = self::constructSelectFields($fields, $selected);
511 $condition_string = DBA::buildCondition($condition);
513 $condition_string = self::addTablesToFields($condition_string, $threadfields);
514 $condition_string = self::addTablesToFields($condition_string, $fields);
517 $condition_string = $condition_string . ' AND ' . self::condition(true);
520 $param_string = DBA::buildParameter($params);
521 $param_string = self::addTablesToFields($param_string, $threadfields);
522 $param_string = self::addTablesToFields($param_string, $fields);
524 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
526 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
528 return DBA::p($sql, $condition);
532 * @brief Returns a list of fields that are associated with the item table
535 * @return array field list
537 private static function fieldlist($usermode)
541 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
542 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
543 'created', 'edited', 'commented', 'received', 'changed', 'psid',
544 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
545 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
546 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
547 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
548 'network' => 'internal-network', 'icid' => 'internal-icid',
549 'iaid' => 'internal-iaid'];
552 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
555 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
557 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
559 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
561 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
563 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
564 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
566 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
567 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
569 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
570 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
571 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
573 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
575 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
577 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
578 'start' => 'event-start','finish' => 'event-finish',
579 'summary' => 'event-summary','desc' => 'event-desc',
580 'location' => 'event-location', 'type' => 'event-type',
581 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
582 'ignore' => 'event-ignore', 'id' => 'event-id'];
584 $fields['sign'] = ['signed_text', 'signature', 'signer'];
586 $fields['diaspora-interaction'] = ['interaction'];
592 * @brief Returns SQL condition for the "select" functions
594 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
596 * @return string SQL condition
598 private static function condition($thread_mode)
601 $master_table = "`thread`";
603 $master_table = "`item`";
605 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
606 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
607 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
608 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
609 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
610 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
611 GRAVITY_PARENT, GRAVITY_PARENT);
615 * @brief Returns all needed "JOIN" commands for the "select" functions
617 * @param integer $uid User ID
618 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
619 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
622 * @return string The SQL joins for the "select" functions
624 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
627 $master_table = "`thread`";
628 $master_table_key = "`thread`.`iid`";
629 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
631 $master_table = "`item`";
632 $master_table_key = "`item`.`id`";
637 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
638 AND NOT `contact`.`blocked`
639 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
640 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
641 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
642 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
643 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
644 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
645 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
646 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
648 if (strpos($sql_commands, "`contact`.") !== false) {
649 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
651 if (strpos($sql_commands, "`author`.") !== false) {
652 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
654 if (strpos($sql_commands, "`owner`.") !== false) {
655 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
659 if (strpos($sql_commands, "`group_member`.") !== false) {
660 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
663 if (strpos($sql_commands, "`user`.") !== false) {
664 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
667 if (strpos($sql_commands, "`event`.") !== false) {
668 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
671 if (strpos($sql_commands, "`sign`.") !== false) {
672 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
675 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
676 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
679 if (strpos($sql_commands, "`item-activity`.") !== false) {
680 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
683 if (strpos($sql_commands, "`item-content`.") !== false) {
684 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
687 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
688 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
691 if (strpos($sql_commands, "`permissionset`.") !== false) {
692 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
695 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
696 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
699 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
700 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
707 * @brief Add the field list for the "select" functions
709 * @param array $fields The field definition array
710 * @param array $selected The array with the selected fields from the "select" functions
712 * @return string The field list
714 private static function constructSelectFields($fields, $selected)
716 if (!empty($selected)) {
717 $selected[] = 'internal-iid';
718 $selected[] = 'internal-iaid';
719 $selected[] = 'internal-icid';
720 $selected[] = 'internal-network';
723 if (in_array('verb', $selected)) {
724 $selected[] = 'internal-activity';
727 if (in_array('ignored', $selected)) {
728 $selected[] = 'internal-user-ignored';
731 if (in_array('signed_text', $selected)) {
732 $selected[] = 'interaction';
735 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
738 foreach ($fields as $table => $table_fields) {
739 foreach ($table_fields as $field => $select) {
740 if (empty($selected) || in_array($select, $selected)) {
741 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
742 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
744 if (is_int($field)) {
745 $selection[] = "`" . $table . "`.`" . $select . "`";
747 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
752 return implode(", ", $selection);
756 * @brief add table definition to fields in an SQL query
758 * @param string $query SQL query
759 * @param array $fields The field definition array
761 * @return string the changed SQL query
763 private static function addTablesToFields($query, $fields)
765 foreach ($fields as $table => $table_fields) {
766 foreach ($table_fields as $alias => $field) {
767 if (is_int($alias)) {
768 $replace_field = $field;
770 $replace_field = $alias;
773 $search = "/([^\.])`" . $field . "`/i";
774 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
775 $query = preg_replace($search, $replace, $query);
782 * @brief Update existing item entries
784 * @param array $fields The fields that are to be changed
785 * @param array $condition The condition for finding the item entries
787 * In the future we may have to change permissions as well.
788 * Then we had to add the user id as third parameter.
790 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
792 * @return integer|boolean number of affected rows - or "false" if there was an error
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
795 public static function update(array $fields, array $condition)
797 if (empty($condition) || empty($fields)) {
801 // To ensure the data integrity we do it in an transaction
804 // We cannot simply expand the condition to check for origin entries
805 // The condition needn't to be a simple array but could be a complex condition.
806 // And we have to execute this query before the update to ensure to fetch the same data.
807 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
809 $content_fields = [];
810 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
811 if (isset($fields[$field])) {
812 $content_fields[$field] = $fields[$field];
813 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
814 unset($fields[$field]);
816 $fields[$field] = null;
821 $delivery_data = ItemDeliveryData::extractFields($fields);
823 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
824 foreach ($clear_fields as $field) {
825 if (array_key_exists($field, $fields)) {
826 $fields[$field] = null;
830 if (array_key_exists('tag', $fields)) {
831 $tags = $fields['tag'];
832 $fields['tag'] = null;
837 if (array_key_exists('file', $fields)) {
838 $files = $fields['file'];
839 $fields['file'] = null;
844 if (!empty($fields)) {
845 $success = DBA::update('item', $fields, $condition);
854 // When there is no content for the "old" item table, this will count the fetched items
855 $rows = DBA::affectedRows();
857 while ($item = DBA::fetch($items)) {
858 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
859 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
861 if (empty($item['iaid'])) {
862 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
863 if (DBA::isResult($item_activity)) {
864 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
865 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
866 if (self::isLegacyMode()) {
867 $item_fields[$field] = null;
869 unset($item_fields[$field]);
872 DBA::update('item', $item_fields, ['id' => $item['id']]);
874 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
875 DBA::delete('item-content', ['id' => $item['icid']]);
878 } elseif (!empty($item['icid'])) {
879 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
881 if (!DBA::exists('item', ['icid' => $item['icid']])) {
882 DBA::delete('item-content', ['id' => $item['icid']]);
886 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
888 if (empty($item['icid'])) {
889 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
890 if (DBA::isResult($item_content)) {
891 $item_fields = ['icid' => $item_content['id']];
892 // Clear all fields in the item table that have a content in the item-content table
893 foreach ($item_content as $field => $content) {
894 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
895 if (self::isLegacyMode()) {
896 $item_fields[$field] = null;
898 unset($item_fields[$field]);
902 DBA::update('item', $item_fields, ['id' => $item['id']]);
907 if (!is_null($tags)) {
908 Term::insertFromTagFieldByItemId($item['id'], $tags);
909 if (!empty($item['tag'])) {
910 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
914 if (!is_null($files)) {
915 Term::insertFromFileFieldByItemId($item['id'], $files);
916 if (!empty($item['file'])) {
917 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
921 ItemDeliveryData::update($item['id'], $delivery_data);
923 self::updateThread($item['id']);
925 // We only need to notfiy others when it is an original entry from us.
926 // Only call the notifier when the item has some content relevant change.
927 if ($item['origin'] && in_array('edited', array_keys($fields))) {
928 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
938 * @brief Delete an item and notify others about it - if it was ours
940 * @param array $condition The condition for finding the item entries
941 * @param integer $priority Priority for the notification
942 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
944 public static function delete($condition, $priority = PRIORITY_HIGH)
946 $items = self::select(['id'], $condition);
947 while ($item = self::fetch($items)) {
948 self::deleteById($item['id'], $priority);
954 * @brief Delete an item for an user and notify others about it - if it was ours
956 * @param array $condition The condition for finding the item entries
957 * @param integer $uid User who wants to delete this item
958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
960 public static function deleteForUser($condition, $uid)
966 $items = self::select(['id', 'uid'], $condition);
967 while ($item = self::fetch($items)) {
968 // "Deleting" global items just means hiding them
969 if ($item['uid'] == 0) {
970 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
971 } elseif ($item['uid'] == $uid) {
972 self::deleteById($item['id'], PRIORITY_HIGH);
974 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
981 * @brief Delete an item and notify others about it - if it was ours
983 * @param integer $item_id Item ID that should be delete
984 * @param integer $priority Priority for the notification
986 * @return boolean success
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
991 // locate item to be deleted
992 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
993 'deleted', 'file', 'resource-id', 'event-id', 'attach',
994 'verb', 'object-type', 'object', 'target', 'contact-id',
995 'icid', 'iaid', 'psid'];
996 $item = self::selectFirst($fields, ['id' => $item_id]);
997 if (!DBA::isResult($item)) {
998 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1002 if ($item['deleted']) {
1003 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1007 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1008 if (!DBA::isResult($parent)) {
1009 $parent = ['origin' => false];
1012 // clean up categories and tags so they don't end up as orphans
1015 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1018 foreach ($matches as $mtch) {
1019 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1025 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1028 foreach ($matches as $mtch) {
1029 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1034 * If item is a link to a photo resource, nuke all the associated photos
1035 * (visitors will not have photo resources)
1036 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1037 * generate a resource-id and therefore aren't intimately linked to the item.
1039 /// @TODO: this should first check if photo is used elsewhere
1040 if (strlen($item['resource-id'])) {
1041 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1044 // If item is a link to an event, delete the event.
1045 if (intval($item['event-id'])) {
1046 Event::delete($item['event-id']);
1049 // If item has attachments, drop them
1050 /// @TODO: this should first check if attachment is used elsewhere
1051 foreach (explode(",", $item['attach']) as $attach) {
1052 preg_match("|attach/(\d+)|", $attach, $matches);
1053 if (is_array($matches) && count($matches) > 1) {
1054 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1058 // Delete tags that had been attached to other items
1059 self::deleteTagsFromItem($item);
1061 // Set the item to "deleted"
1062 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1063 DBA::update('item', $item_fields, ['id' => $item['id']]);
1065 Term::insertFromTagFieldByItemId($item['id'], '');
1066 Term::insertFromFileFieldByItemId($item['id'], '');
1067 self::deleteThread($item['id'], $item['parent-uri']);
1069 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1070 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1073 ItemDeliveryData::delete($item['id']);
1075 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1077 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1078 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1080 // When the permission set will be used in photo and events as well,
1081 // this query here needs to be extended.
1082 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1083 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1086 // If it's the parent of a comment thread, kill all the kids
1087 if ($item['id'] == $item['parent']) {
1088 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1091 // Is it our comment and/or our thread?
1092 if ($item['origin'] || $parent['origin']) {
1094 // When we delete the original post we will delete all existing copies on the server as well
1095 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1097 // send the notification upstream/downstream
1098 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1099 } elseif ($item['uid'] != 0) {
1101 // When we delete just our local user copy of an item, we have to set a marker to hide it
1102 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1103 if (DBA::isResult($global_item)) {
1104 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1108 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1113 private static function deleteTagsFromItem($item)
1115 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1119 $xo = XML::parseString($item["object"], false);
1120 $xt = XML::parseString($item["target"], false);
1122 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1126 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1127 if (!DBA::isResult($i)) {
1131 // For tags, the owner cannot remove the tag on the author's copy of the post.
1132 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1133 $author_copy = $item["origin"];
1135 if (($owner_remove && $author_copy) || !$owner_remove) {
1139 $tags = explode(',', $i["tag"]);
1142 foreach ($tags as $tag) {
1143 if (trim($tag) !== trim($xo->body)) {
1144 $newtags[] = trim($tag);
1148 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1151 private static function guid($item, $notify)
1153 if (!empty($item['guid'])) {
1154 return Strings::escapeTags(trim($item['guid']));
1158 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1159 // We add the hash of our own host because our host is the original creator of the post.
1160 $prefix_host = \get_app()->getHostName();
1164 // We are only storing the post so we create a GUID from the original hostname.
1165 if (!empty($item['author-link'])) {
1166 $parsed = parse_url($item['author-link']);
1167 if (!empty($parsed['host'])) {
1168 $prefix_host = $parsed['host'];
1172 if (empty($prefix_host) && !empty($item['plink'])) {
1173 $parsed = parse_url($item['plink']);
1174 if (!empty($parsed['host'])) {
1175 $prefix_host = $parsed['host'];
1179 if (empty($prefix_host) && !empty($item['uri'])) {
1180 $parsed = parse_url($item['uri']);
1181 if (!empty($parsed['host'])) {
1182 $prefix_host = $parsed['host'];
1186 // Is it in the format data@host.tld? - Used for mail contacts
1187 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1188 $mailparts = explode('@', $item['author-link']);
1189 $prefix_host = array_pop($mailparts);
1193 if (!empty($item['plink'])) {
1194 $guid = self::guidFromUri($item['plink'], $prefix_host);
1195 } elseif (!empty($item['uri'])) {
1196 $guid = self::guidFromUri($item['uri'], $prefix_host);
1198 $guid = System::createUUID(hash('crc32', $prefix_host));
1204 private static function contactId($item)
1206 $contact_id = (int)$item["contact-id"];
1208 if (!empty($contact_id)) {
1211 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1213 * First we are looking for a suitable contact that matches with the author of the post
1214 * This is done only for comments
1216 if ($item['parent-uri'] != $item['uri']) {
1217 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1220 // If not present then maybe the owner was found
1221 if ($contact_id == 0) {
1222 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1225 // Still missing? Then use the "self" contact of the current user
1226 if ($contact_id == 0) {
1227 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1228 if (DBA::isResult($self)) {
1229 $contact_id = $self["id"];
1232 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1237 // This function will finally cover most of the preparation functionality in mod/item.php
1238 public static function prepare(&$item)
1241 * @TODO: Unused code triggering inspection errors
1243 $data = BBCode::getAttachmentData($item['body']);
1244 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1245 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1246 $posttype = Item::PT_PAGE;
1247 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1252 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1256 $priority = PRIORITY_HIGH;
1258 // If it is a posting where users should get notifications, then define it as wall posting
1261 $item['origin'] = 1;
1262 $item['network'] = Protocol::DFRN;
1263 $item['protocol'] = Conversation::PARCEL_DFRN;
1265 if (is_int($notify)) {
1266 $priority = $notify;
1269 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1272 $item['guid'] = self::guid($item, $notify);
1273 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1276 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1278 // Store conversation data
1279 $item = Conversation::insert($item);
1282 * If a Diaspora signature structure was passed in, pull it out of the
1283 * item array and set it aside for later storage.
1287 if (isset($item['dsprsig'])) {
1288 $encoded_signature = $item['dsprsig'];
1289 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1290 unset($item['dsprsig']);
1293 $diaspora_signed_text = '';
1294 if (isset($item['diaspora_signed_text'])) {
1295 $diaspora_signed_text = $item['diaspora_signed_text'];
1296 unset($item['diaspora_signed_text']);
1299 // Converting the plink
1300 /// @TODO Check if this is really still needed
1301 if ($item['network'] == Protocol::OSTATUS) {
1302 if (isset($item['plink'])) {
1303 $item['plink'] = OStatus::convertHref($item['plink']);
1304 } elseif (isset($item['uri'])) {
1305 $item['plink'] = OStatus::convertHref($item['uri']);
1309 if (!empty($item['thr-parent'])) {
1310 $item['parent-uri'] = $item['thr-parent'];
1313 if (isset($item['gravity'])) {
1314 $item['gravity'] = intval($item['gravity']);
1315 } elseif ($item['parent-uri'] === $item['uri']) {
1316 $item['gravity'] = GRAVITY_PARENT;
1317 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1318 $item['gravity'] = GRAVITY_COMMENT;
1319 } elseif (activity_match($item['verb'], ACTIVITY_FOLLOW)) {
1320 $item['gravity'] = GRAVITY_ACTIVITY;
1322 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1323 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1326 $uid = intval($item['uid']);
1328 // check for create date and expire time
1329 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1331 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1332 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1333 $expire_interval = $user['expire'];
1336 if (($expire_interval > 0) && !empty($item['created'])) {
1337 $expire_date = time() - ($expire_interval * 86400);
1338 $created_date = strtotime($item['created']);
1339 if ($created_date < $expire_date) {
1340 Logger::notice('Item created before expiration interval.', [
1341 'created' => date('c', $created_date),
1342 'expired' => date('c', $expire_date),
1350 * Do we already have this item?
1351 * We have to check several networks since Friendica posts could be repeated
1352 * via OStatus (maybe Diasporsa as well)
1354 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1355 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1356 trim($item['uri']), $item['uid'],
1357 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1358 $existing = self::selectFirst(['id', 'network'], $condition);
1359 if (DBA::isResult($existing)) {
1360 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1362 Logger::notice('Item already existed for user', [
1363 'uri' => $item['uri'],
1365 'network' => $item['network'],
1366 'existing_id' => $existing["id"],
1367 'existing_network' => $existing["network"]
1371 return $existing["id"];
1375 $item['wall'] = intval(defaults($item, 'wall', 0));
1376 $item['extid'] = trim(defaults($item, 'extid', ''));
1377 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1378 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1379 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1380 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1381 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1382 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1383 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1384 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1385 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1386 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1387 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1388 $item['title'] = trim(defaults($item, 'title', ''));
1389 $item['location'] = trim(defaults($item, 'location', ''));
1390 $item['coord'] = trim(defaults($item, 'coord', ''));
1391 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1392 $item['deleted'] = 0;
1393 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1394 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1395 $item['verb'] = trim(defaults($item, 'verb', ''));
1396 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1397 $item['object'] = trim(defaults($item, 'object', ''));
1398 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1399 $item['target'] = trim(defaults($item, 'target', ''));
1400 $item['plink'] = trim(defaults($item, 'plink', ''));
1401 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1402 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1403 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1404 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1405 $item['private'] = intval(defaults($item, 'private', 0));
1406 $item['body'] = trim(defaults($item, 'body', ''));
1407 $item['tag'] = trim(defaults($item, 'tag', ''));
1408 $item['attach'] = trim(defaults($item, 'attach', ''));
1409 $item['app'] = trim(defaults($item, 'app', ''));
1410 $item['origin'] = intval(defaults($item, 'origin', 0));
1411 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1412 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1413 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1414 $item['inform'] = trim(defaults($item, 'inform', ''));
1415 $item['file'] = trim(defaults($item, 'file', ''));
1417 // When there is no content then we don't post it
1418 if ($item['body'].$item['title'] == '') {
1419 Logger::notice('No body, no title.');
1423 self::addLanguageToItemArray($item);
1425 // Items cannot be stored before they happen ...
1426 if ($item['created'] > DateTimeFormat::utcNow()) {
1427 $item['created'] = DateTimeFormat::utcNow();
1430 // We haven't invented time travel by now.
1431 if ($item['edited'] > DateTimeFormat::utcNow()) {
1432 $item['edited'] = DateTimeFormat::utcNow();
1435 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1437 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1438 $item["contact-id"] = self::contactId($item);
1440 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1441 'photo' => $item['author-avatar'], 'network' => $item['network']];
1443 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item['author-link'], 0, false, $default));
1445 if (Contact::isBlocked($item['author-id'])) {
1446 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1450 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1451 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1455 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1456 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1458 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item['owner-link'], 0, false, $default));
1460 if (Contact::isBlocked($item['owner-id'])) {
1461 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1465 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1466 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1470 if ($item['network'] == Protocol::PHANTOM) {
1471 $item['network'] = Protocol::DFRN;
1472 Logger::notice('Missing network, setting to {network}.', [
1473 'uri' => $item["uri"],
1474 'network' => $item['network'],
1475 'callstack' => System::callstack()
1479 // Checking if there is already an item with the same guid
1480 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1481 if (self::exists($condition)) {
1482 Logger::notice('Found already existing item', [
1483 'guid' => $item['guid'],
1484 'uid' => $item['uid'],
1485 'network' => $item['network']
1490 if ($item['verb'] == ACTIVITY_FOLLOW) {
1491 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1492 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1493 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1497 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => $item['uid'],
1498 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1499 if (self::exists($condition)) {
1500 // It happens that we receive multiple follow requests by the same author - we only store one.
1501 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1506 // Check for hashtags in the body and repair or add hashtag links
1507 self::setHashtags($item);
1509 $item['thr-parent'] = $item['parent-uri'];
1517 if ($item['parent-uri'] === $item['uri']) {
1519 $parent_deleted = 0;
1520 $allow_cid = $item['allow_cid'];
1521 $allow_gid = $item['allow_gid'];
1522 $deny_cid = $item['deny_cid'];
1523 $deny_gid = $item['deny_gid'];
1524 $notify_type = 'wall-new';
1526 // find the parent and snarf the item id and ACLs
1527 // and anything else we need to inherit
1529 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1530 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1531 'wall', 'private', 'forum_mode', 'origin'];
1532 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1533 $params = ['order' => ['id' => false]];
1534 $parent = self::selectFirst($fields, $condition, $params);
1536 if (DBA::isResult($parent)) {
1537 // is the new message multi-level threaded?
1538 // even though we don't support it now, preserve the info
1539 // and re-attach to the conversation parent.
1541 if ($parent['uri'] != $parent['parent-uri']) {
1542 $item['parent-uri'] = $parent['parent-uri'];
1544 $condition = ['uri' => $item['parent-uri'],
1545 'parent-uri' => $item['parent-uri'],
1546 'uid' => $item['uid']];
1547 $params = ['order' => ['id' => false]];
1548 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1550 if (DBA::isResult($toplevel_parent)) {
1551 $parent = $toplevel_parent;
1555 $parent_id = $parent['id'];
1556 $parent_deleted = $parent['deleted'];
1557 $allow_cid = $parent['allow_cid'];
1558 $allow_gid = $parent['allow_gid'];
1559 $deny_cid = $parent['deny_cid'];
1560 $deny_gid = $parent['deny_gid'];
1561 $item['wall'] = $parent['wall'];
1562 $notify_type = 'comment-new';
1565 * If the parent is private, force privacy for the entire conversation
1566 * This differs from the above settings as it subtly allows comments from
1567 * email correspondents to be private even if the overall thread is not.
1569 if ($parent['private']) {
1570 $item['private'] = $parent['private'];
1574 * Edge case. We host a public forum that was originally posted to privately.
1575 * The original author commented, but as this is a comment, the permissions
1576 * weren't fixed up so it will still show the comment as private unless we fix it here.
1578 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1579 $item['private'] = 0;
1582 // If its a post that originated here then tag the thread as "mention"
1583 if ($item['origin'] && $item['uid']) {
1584 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1585 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1589 * Allow one to see reply tweets from status.net even when
1590 * we don't have or can't see the original post.
1592 if ($force_parent) {
1593 Logger::log('$force_parent=true, reply converted to top-level post.');
1595 $item['parent-uri'] = $item['uri'];
1596 $item['gravity'] = GRAVITY_PARENT;
1598 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1602 $parent_deleted = 0;
1606 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1607 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1609 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1610 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1611 if (self::exists($condition)) {
1612 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1616 // On Friendica and Diaspora the GUID is unique
1617 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1618 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1619 if (self::exists($condition)) {
1620 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1624 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1625 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1626 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1627 if (self::exists($condition)) {
1628 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1633 // Is this item available in the global items (with uid=0)?
1634 if ($item["uid"] == 0) {
1635 $item["global"] = true;
1637 // Set the global flag on all items if this was a global item entry
1638 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1640 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1644 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1647 $private = $item['private'];
1650 $item["allow_cid"] = $allow_cid;
1651 $item["allow_gid"] = $allow_gid;
1652 $item["deny_cid"] = $deny_cid;
1653 $item["deny_gid"] = $deny_gid;
1654 $item["private"] = $private;
1655 $item["deleted"] = $parent_deleted;
1657 // Fill the cache field
1658 self::putInCache($item);
1661 $item['edit'] = false;
1662 $item['parent'] = $parent_id;
1663 Hook::callAll('post_local', $item);
1664 unset($item['edit']);
1665 unset($item['parent']);
1667 Hook::callAll('post_remote', $item);
1670 // This array field is used to trigger some automatic reactions
1671 // It is mainly used in the "post_local" hook.
1672 unset($item['api_source']);
1674 if (!empty($item['cancel'])) {
1675 Logger::log('post cancelled by addon.');
1680 * Check for already added items.
1681 * There is a timing issue here that sometimes creates double postings.
1682 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1684 if ($item["uid"] == 0) {
1685 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1686 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1691 Logger::log('' . print_r($item,true), Logger::DATA);
1693 if (array_key_exists('tag', $item)) {
1694 $tags = $item['tag'];
1695 unset($item['tag']);
1700 if (array_key_exists('file', $item)) {
1701 $files = $item['file'];
1702 unset($item['file']);
1707 // Creates or assigns the permission set
1708 $item['psid'] = PermissionSet::fetchIDForPost($item);
1710 // We are doing this outside of the transaction to avoid timing problems
1711 if (!self::insertActivity($item)) {
1712 self::insertContent($item);
1715 $delivery_data = ItemDeliveryData::extractFields($item);
1717 unset($item['postopts']);
1718 unset($item['inform']);
1720 // These fields aren't stored anymore in the item table, they are fetched upon request
1721 unset($item['author-link']);
1722 unset($item['author-name']);
1723 unset($item['author-avatar']);
1725 unset($item['owner-link']);
1726 unset($item['owner-name']);
1727 unset($item['owner-avatar']);
1730 $ret = DBA::insert('item', $item);
1732 // When the item was successfully stored we fetch the ID of the item.
1733 if (DBA::isResult($ret)) {
1734 $current_post = DBA::lastInsertId();
1736 // This can happen - for example - if there are locking timeouts.
1739 // Store the data into a spool file so that we can try again later.
1741 // At first we restore the Diaspora signature that we removed above.
1742 if (isset($encoded_signature)) {
1743 $item['dsprsig'] = $encoded_signature;
1746 // Now we store the data in the spool directory
1747 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1748 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1750 $spoolpath = get_spoolpath();
1751 if ($spoolpath != "") {
1752 $spool = $spoolpath.'/'.$file;
1754 file_put_contents($spool, json_encode($orig_item));
1755 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1760 if ($current_post == 0) {
1761 // This is one of these error messages that never should occur.
1762 Logger::log("couldn't find created item - we better quit now.");
1767 // How much entries have we created?
1768 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1769 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1772 // There are duplicates. We delete our just created entry.
1773 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1775 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1776 DBA::delete('item', ['id' => $current_post]);
1779 } elseif ($entries == 0) {
1780 // This really should never happen since we quit earlier if there were problems.
1781 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1786 Logger::log('created item '.$current_post);
1787 self::updateContact($item);
1789 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1790 $parent_id = $current_post;
1794 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1796 $item['id'] = $current_post;
1797 $item['parent'] = $parent_id;
1799 // update the commented timestamp on the parent
1800 // Only update "commented" if it is really a comment
1801 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1802 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1804 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1809 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1810 * We can check for this condition when we decode and encode the stuff again.
1812 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1813 $dsprsig->signature = base64_decode($dsprsig->signature);
1814 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1817 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1818 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1820 // The other fields are used by very old Friendica servers, so we currently store them differently
1821 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1822 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1826 if (!empty($diaspora_signed_text)) {
1827 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1830 self::tagDeliver($item['uid'], $current_post);
1833 * current post can be deleted if is for a community page and no mention are
1837 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1838 if (DBA::isResult($posted_item)) {
1840 Hook::callAll('post_local_end', $posted_item);
1842 Hook::callAll('post_remote_end', $posted_item);
1845 Logger::log('new item not found in DB, id ' . $current_post);
1849 if ($item['parent-uri'] === $item['uri']) {
1850 self::addThread($current_post);
1852 self::updateThread($parent_id);
1855 ItemDeliveryData::insert($current_post, $delivery_data);
1860 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1861 * This is not perfect - but a workable solution until we found the reason for the problem.
1863 if (!empty($tags)) {
1864 Term::insertFromTagFieldByItemId($current_post, $tags);
1867 if (!empty($files)) {
1868 Term::insertFromFileFieldByItemId($current_post, $files);
1871 if ($item['parent-uri'] === $item['uri']) {
1872 self::addShadow($current_post);
1874 self::addShadowPost($current_post);
1877 check_user_notification($current_post);
1880 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1881 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1882 if ($item['gravity'] == GRAVITY_ACTIVITY) {
1883 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1884 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1885 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1890 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1893 return $current_post;
1897 * @brief Insert a new item content entry
1899 * @param array $item The item fields that are to be inserted
1901 * @throws \Exception
1903 private static function insertActivity(&$item)
1905 $activity_index = self::activityToIndex($item['verb']);
1907 if ($activity_index < 0) {
1911 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1913 // We just remove everything that is content
1914 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1915 unset($item[$field]);
1918 // To avoid timing problems, we are using locks.
1919 $locked = Lock::acquire('item_insert_activity');
1921 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1924 // Do we already have this content?
1925 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1926 if (DBA::isResult($item_activity)) {
1927 $item['iaid'] = $item_activity['id'];
1928 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1929 } elseif (DBA::insert('item-activity', $fields)) {
1930 $item['iaid'] = DBA::lastInsertId();
1931 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1933 // This shouldn't happen.
1934 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1935 Lock::release('item_insert_activity');
1939 Lock::release('item_insert_activity');
1945 * @brief Insert a new item content entry
1947 * @param array $item The item fields that are to be inserted
1948 * @throws \Exception
1950 private static function insertContent(&$item)
1952 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1954 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1955 if (isset($item[$field])) {
1956 $fields[$field] = $item[$field];
1957 unset($item[$field]);
1961 // To avoid timing problems, we are using locks.
1962 $locked = Lock::acquire('item_insert_content');
1964 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1967 // Do we already have this content?
1968 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1969 if (DBA::isResult($item_content)) {
1970 $item['icid'] = $item_content['id'];
1971 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1972 } elseif (DBA::insert('item-content', $fields)) {
1973 $item['icid'] = DBA::lastInsertId();
1974 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1976 // This shouldn't happen.
1977 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1980 Lock::release('item_insert_content');
1985 * @brief Update existing item content entries
1987 * @param array $item The item fields that are to be changed
1988 * @param array $condition The condition for finding the item content entries
1990 * @throws \Exception
1992 private static function updateActivity($item, $condition)
1994 if (empty($item['verb'])) {
1997 $activity_index = self::activityToIndex($item['verb']);
1999 if ($activity_index < 0) {
2003 $fields = ['activity' => $activity_index];
2005 Logger::log('Update activity for ' . json_encode($condition));
2007 DBA::update('item-activity', $fields, $condition, true);
2013 * @brief Update existing item content entries
2015 * @param array $item The item fields that are to be changed
2016 * @param array $condition The condition for finding the item content entries
2017 * @throws \Exception
2019 private static function updateContent($item, $condition)
2021 // We have to select only the fields from the "item-content" table
2023 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2024 if (isset($item[$field])) {
2025 $fields[$field] = $item[$field];
2029 if (empty($fields)) {
2030 // when there are no fields at all, just use the condition
2031 // This is to ensure that we always store content.
2032 $fields = $condition;
2035 Logger::log('Update content for ' . json_encode($condition));
2037 DBA::update('item-content', $fields, $condition, true);
2041 * @brief Distributes public items to the receivers
2043 * @param integer $itemid Item ID that should be added
2044 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2045 * @throws \Exception
2047 public static function distribute($itemid, $signed_text = '')
2049 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2050 $parent = self::selectFirst(['owner-id'], $condition);
2051 if (!DBA::isResult($parent)) {
2055 // Only distribute public items from native networks
2056 $condition = ['id' => $itemid, 'uid' => 0,
2057 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2058 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2059 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2060 if (!DBA::isResult($item)) {
2064 $origin = $item['origin'];
2067 unset($item['parent']);
2068 unset($item['mention']);
2069 unset($item['wall']);
2070 unset($item['origin']);
2071 unset($item['starred']);
2075 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2076 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2077 if (!DBA::isResult($owner)) {
2081 $condition = ['nurl' => $owner['nurl'], '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 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2093 $contacts = DBA::select('contact', ['uid'], $condition);
2094 while ($contact = DBA::fetch($contacts)) {
2095 if ($contact['uid'] == 0) {
2099 $users[$contact['uid']] = $contact['uid'];
2101 DBA::close($contacts);
2103 if (!empty($owner['alias'])) {
2104 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2105 $contacts = DBA::select('contact', ['uid'], $condition);
2106 while ($contact = DBA::fetch($contacts)) {
2107 if ($contact['uid'] == 0) {
2111 $users[$contact['uid']] = $contact['uid'];
2113 DBA::close($contacts);
2118 if ($item['uri'] != $item['parent-uri']) {
2119 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2120 while ($parent = self::fetch($parents)) {
2121 $users[$parent['uid']] = $parent['uid'];
2122 if ($parent['origin'] && !$origin) {
2123 $origin_uid = $parent['uid'];
2128 foreach ($users as $uid) {
2129 if ($origin_uid == $uid) {
2130 $item['diaspora_signed_text'] = $signed_text;
2132 self::storeForUser($itemid, $item, $uid);
2137 * @brief Store public items for the receivers
2139 * @param integer $itemid Item ID that should be added
2140 * @param array $item The item entry that will be stored
2141 * @param integer $uid The user that will receive the item entry
2142 * @throws \Exception
2144 private static function storeForUser($itemid, $item, $uid)
2146 $item['uid'] = $uid;
2147 $item['origin'] = 0;
2149 if ($item['uri'] == $item['parent-uri']) {
2150 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2152 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2155 if (empty($item['contact-id'])) {
2156 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2157 if (!DBA::isResult($self)) {
2160 $item['contact-id'] = $self['id'];
2163 /// @todo Handling of "event-id"
2166 if ($item['uri'] == $item['parent-uri']) {
2167 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2168 if (DBA::isResult($contact)) {
2169 $notify = self::isRemoteSelf($contact, $item);
2173 $distributed = self::insert($item, false, $notify, true);
2175 if (!$distributed) {
2176 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2178 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2183 * @brief Add a shadow entry for a given item id that is a thread starter
2185 * We store every public item entry additionally with the user id "0".
2186 * This is used for the community page and for the search.
2187 * It is planned that in the future we will store public item entries only once.
2189 * @param integer $itemid Item ID that should be added
2190 * @throws \Exception
2192 public static function addShadow($itemid)
2194 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2195 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2196 $item = self::selectFirst($fields, $condition);
2198 if (!DBA::isResult($item)) {
2202 // is it already a copy?
2203 if (($itemid == 0) || ($item['uid'] == 0)) {
2207 // Is it a visible public post?
2208 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2212 // is it an entry from a connector? Only add an entry for natively connected networks
2213 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2217 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2221 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2223 if (DBA::isResult($item)) {
2224 // Preparing public shadow (removing user specific data)
2227 unset($item['parent']);
2228 unset($item['wall']);
2229 unset($item['mention']);
2230 unset($item['origin']);
2231 unset($item['starred']);
2232 unset($item['postopts']);
2233 unset($item['inform']);
2234 if ($item['uri'] == $item['parent-uri']) {
2235 $item['contact-id'] = $item['owner-id'];
2237 $item['contact-id'] = $item['author-id'];
2240 $public_shadow = self::insert($item, false, false, true);
2242 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2247 * @brief Add a shadow entry for a given item id that is a comment
2249 * This function does the same like the function above - but for comments
2251 * @param integer $itemid Item ID that should be added
2252 * @throws \Exception
2254 public static function addShadowPost($itemid)
2256 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2257 if (!DBA::isResult($item)) {
2261 // Is it a toplevel post?
2262 if ($item['id'] == $item['parent']) {
2263 self::addShadow($itemid);
2267 // Is this a shadow entry?
2268 if ($item['uid'] == 0) {
2272 // Is there a shadow parent?
2273 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2277 // Is there already a shadow entry?
2278 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2282 // Save "origin" and "parent" state
2283 $origin = $item['origin'];
2284 $parent = $item['parent'];
2286 // Preparing public shadow (removing user specific data)
2289 unset($item['parent']);
2290 unset($item['wall']);
2291 unset($item['mention']);
2292 unset($item['origin']);
2293 unset($item['starred']);
2294 unset($item['postopts']);
2295 unset($item['inform']);
2296 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2298 $public_shadow = self::insert($item, false, false, true);
2300 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2302 // If this was a comment to a Diaspora post we don't get our comment back.
2303 // This means that we have to distribute the comment by ourselves.
2304 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2305 self::distribute($public_shadow);
2310 * Adds a language specification in a "language" element of given $arr.
2311 * Expects "body" element to exist in $arr.
2314 * @throws \Text_LanguageDetect_Exception
2316 private static function addLanguageToItemArray(&$item)
2318 $naked_body = BBCode::toPlaintext($item['body'], false);
2320 $ld = new Text_LanguageDetect();
2321 $ld->setNameMode(2);
2322 $languages = $ld->detect($naked_body, 3);
2324 if (is_array($languages)) {
2325 $item['language'] = json_encode($languages);
2330 * @brief Creates an unique guid out of a given uri
2332 * @param string $uri uri of an item entry
2333 * @param string $host hostname for the GUID prefix
2334 * @return string unique guid
2336 public static function guidFromUri($uri, $host)
2338 // Our regular guid routine is using this kind of prefix as well
2339 // We have to avoid that different routines could accidentally create the same value
2340 $parsed = parse_url($uri);
2342 // We use a hash of the hostname as prefix for the guid
2343 $guid_prefix = hash("crc32", $host);
2345 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2346 unset($parsed["scheme"]);
2348 // Glue it together to be able to make a hash from it
2349 $host_id = implode("/", $parsed);
2351 // We could use any hash algorithm since it isn't a security issue
2352 $host_hash = hash("ripemd128", $host_id);
2354 return $guid_prefix.$host_hash;
2358 * generate an unique URI
2360 * @param integer $uid User id
2361 * @param string $guid An existing GUID (Otherwise it will be generated)
2364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2366 public static function newURI($uid, $guid = "")
2369 $guid = System::createUUID();
2372 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2376 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2378 * This can be used to filter for inactive contacts.
2379 * Only do this for public postings to avoid privacy problems, since poco data is public.
2380 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2382 * @param array $arr Contains the just posted item record
2383 * @throws \Exception
2385 private static function updateContact($arr)
2387 // Unarchive the author
2388 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2389 if (DBA::isResult($contact)) {
2390 Contact::unmarkForArchival($contact);
2393 // Unarchive the contact if it's not our own contact
2394 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2395 if (DBA::isResult($contact)) {
2396 Contact::unmarkForArchival($contact);
2399 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2401 // Is it a forum? Then we don't care about the rules from above
2402 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2403 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2409 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2410 ['id' => $arr['contact-id']]);
2412 // Now do the same for the system wide contacts with uid=0
2413 if (!$arr['private']) {
2414 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2415 ['id' => $arr['owner-id']]);
2417 if ($arr['owner-id'] != $arr['author-id']) {
2418 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2419 ['id' => $arr['author-id']]);
2424 public static function setHashtags(&$item)
2426 $tags = BBCode::getTags($item["body"]);
2429 if (!count($tags)) {
2433 // What happens in [code], stays in [code]!
2434 // escape the # and the [
2435 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2436 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2438 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2440 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2441 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2444 // This sorting is important when there are hashtags that are part of other hashtags
2445 // Otherwise there could be problems with hashtags like #test and #test2
2448 $URLSearchString = "^\[\]";
2450 // All hashtags should point to the home server if "local_tags" is activated
2451 if (Config::get('system', 'local_tags')) {
2452 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2453 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2455 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2456 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2459 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2460 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2462 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2465 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2467 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2470 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2472 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2475 // Repair recursive urls
2476 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2477 "#$2", $item["body"]);
2479 foreach ($tags as $tag) {
2480 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
2484 $basetag = str_replace('_',' ',substr($tag,1));
2485 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2487 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2489 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2490 if (strlen($item["tag"])) {
2491 $item["tag"] = ',' . $item["tag"];
2493 $item["tag"] = $newtag . $item["tag"];
2497 // Convert back the masked hashtags
2498 $item["body"] = str_replace("#", "#", $item["body"]);
2500 // Remember! What happens in [code], stays in [code]
2501 // roleback the # and [
2502 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2504 // we truly unESCape all sharp and leftsquarebracket
2505 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2506 $replace = ['#', '['];
2507 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2511 public static function getGuidById($id)
2513 $item = self::selectFirst(['guid'], ['id' => $id]);
2514 if (DBA::isResult($item)) {
2515 return $item['guid'];
2522 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2524 * @param string $guid item guid
2525 * @param int $uid user id
2526 * @return array with id and nick of the item with the given guid
2527 * @throws \Exception
2529 public static function getIdAndNickByGuid($guid, $uid = 0)
2535 $uid = local_user();
2538 // Does the given user have this item?
2540 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2541 if (DBA::isResult($item)) {
2542 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2543 if (!DBA::isResult($user)) {
2547 $nick = $user['nickname'];
2551 // Or is it anywhere on the server?
2553 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2554 $item = self::selectFirst(['id', 'uid'], $condition);
2555 if (DBA::isResult($item)) {
2556 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2557 if (!DBA::isResult($user)) {
2561 $nick = $user['nickname'];
2564 return ["nick" => $nick, "id" => $id];
2568 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2571 * @param int $item_id
2572 * @return void true if item was deleted, else false
2573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2574 * @throws \ImagickException
2576 private static function tagDeliver($uid, $item_id)
2580 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2581 if (!DBA::isResult($user)) {
2585 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2586 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2588 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2589 if (!DBA::isResult($item)) {
2593 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2596 * Diaspora uses their own hardwired link URL in @-tags
2597 * instead of the one we supply with webfinger
2599 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2601 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2603 foreach ($matches as $mtch) {
2604 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2606 Logger::log('mention found: ' . $mtch[2]);
2612 if (($community_page || $prvgroup) &&
2613 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2614 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2616 Logger::log("no-mention top-level post to community or private group. delete.");
2617 DBA::delete('item', ['id' => $item_id]);
2623 $arr = ['item' => $item, 'user' => $user];
2625 Hook::callAll('tagged', $arr);
2627 if (!$community_page && !$prvgroup) {
2632 * tgroup delivery - setup a second delivery chain
2633 * prevent delivery looping - only proceed
2634 * if the message originated elsewhere and is a top-level post
2636 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2640 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2641 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2642 if (!DBA::isResult($self)) {
2646 $owner_id = Contact::getIdForURL($self['url']);
2648 // also reset all the privacy bits to the forum default permissions
2650 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2652 $psid = PermissionSet::fetchIDForPost($user);
2654 $forum_mode = ($prvgroup ? 2 : 1);
2656 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2657 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2658 self::update($fields, ['id' => $item_id]);
2660 self::updateThread($item_id);
2662 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2665 public static function isRemoteSelf($contact, &$datarray)
2669 if (!$contact['remote_self']) {
2673 // Prevent the forwarding of posts that are forwarded
2674 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2675 Logger::log('Already forwarded', Logger::DEBUG);
2679 // Prevent to forward already forwarded posts
2680 if ($datarray["app"] == $a->getHostName()) {
2681 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2685 // Only forward posts
2686 if ($datarray["verb"] != ACTIVITY_POST) {
2687 Logger::log('No post', Logger::DEBUG);
2691 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2692 Logger::log('Not public', Logger::DEBUG);
2696 $datarray2 = $datarray;
2697 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2698 if ($contact['remote_self'] == 2) {
2699 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2700 ['uid' => $contact['uid'], 'self' => true]);
2701 if (DBA::isResult($self)) {
2702 $datarray['contact-id'] = $self["id"];
2704 $datarray['owner-name'] = $self["name"];
2705 $datarray['owner-link'] = $self["url"];
2706 $datarray['owner-avatar'] = $self["thumb"];
2708 $datarray['author-name'] = $datarray['owner-name'];
2709 $datarray['author-link'] = $datarray['owner-link'];
2710 $datarray['author-avatar'] = $datarray['owner-avatar'];
2712 unset($datarray['created']);
2713 unset($datarray['edited']);
2715 unset($datarray['network']);
2716 unset($datarray['owner-id']);
2717 unset($datarray['author-id']);
2720 if ($contact['network'] != Protocol::FEED) {
2721 $datarray["guid"] = System::createUUID();
2722 unset($datarray["plink"]);
2723 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2724 $datarray["parent-uri"] = $datarray["uri"];
2725 $datarray["thr-parent"] = $datarray["uri"];
2726 $datarray["extid"] = Protocol::DFRN;
2727 $urlpart = parse_url($datarray2['author-link']);
2728 $datarray["app"] = $urlpart["host"];
2730 $datarray['private'] = 0;
2734 if ($contact['network'] != Protocol::FEED) {
2735 // Store the original post
2736 $result = self::insert($datarray2, false, false);
2737 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2739 $datarray["app"] = "Feed";
2743 // Trigger automatic reactions for addons
2744 $datarray['api_source'] = true;
2746 // We have to tell the hooks who we are - this really should be improved
2747 $_SESSION["authenticated"] = true;
2748 $_SESSION["uid"] = $contact['uid'];
2757 * @param array $item
2760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2761 * @throws \ImagickException
2763 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2765 if (Config::get('system', 'disable_embedded')) {
2769 Logger::log('check for photos', Logger::DEBUG);
2770 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2775 $img_start = strpos($orig_body, '[img');
2776 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2777 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2779 while (($img_st_close !== false) && ($img_len !== false)) {
2780 $img_st_close++; // make it point to AFTER the closing bracket
2781 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2783 Logger::log('found photo ' . $image, Logger::DEBUG);
2785 if (stristr($image, $site . '/photo/')) {
2786 // Only embed locally hosted photos
2788 $i = basename($image);
2789 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2790 $x = strpos($i, '-');
2793 $res = substr($i, $x + 1);
2794 $i = substr($i, 0, $x);
2795 $photo = Photo::getPhotoForUser($uid, $i, $res);
2796 if (DBA::isResult($photo)) {
2798 * Check to see if we should replace this photo link with an embedded image
2799 * 1. No need to do so if the photo is public
2800 * 2. If there's a contact-id provided, see if they're in the access list
2801 * for the photo. If so, embed it.
2802 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2803 * permissions, regardless of order but first check to see if they're an exact
2804 * match to save some processing overhead.
2806 if (self::hasPermissions($photo)) {
2808 $recips = self::enumeratePermissions($photo);
2809 if (in_array($cid, $recips)) {
2813 if (self::samePermissions($item, $photo)) {
2819 $photo_img = Photo::getImageForPhoto($photo);
2820 // If a custom width and height were specified, apply before embedding
2821 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2822 Logger::log('scaling photo', Logger::DEBUG);
2824 $width = intval($match[1]);
2825 $height = intval($match[2]);
2827 $photo_img->scaleDown(max($width, $height));
2830 $data = $photo_img->asString();
2831 $type = $photo_img->getType();
2833 Logger::log('replacing photo', Logger::DEBUG);
2834 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2835 Logger::log('replaced: ' . $image, Logger::DATA);
2841 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2842 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2843 if ($orig_body === false) {
2847 $img_start = strpos($orig_body, '[img');
2848 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2849 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2852 $new_body = $new_body . $orig_body;
2857 private static function hasPermissions($obj)
2859 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2860 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2863 private static function samePermissions($obj1, $obj2)
2865 // first part is easy. Check that these are exactly the same.
2866 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2867 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2868 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2869 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2873 // This is harder. Parse all the permissions and compare the resulting set.
2874 $recipients1 = self::enumeratePermissions($obj1);
2875 $recipients2 = self::enumeratePermissions($obj2);
2879 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2880 return ($recipients1 == $recipients2);
2883 // returns an array of contact-ids that are allowed to see this object
2884 public static function enumeratePermissions($obj)
2886 $allow_people = expand_acl($obj['allow_cid']);
2887 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2888 $deny_people = expand_acl($obj['deny_cid']);
2889 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2890 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2891 $deny = array_unique(array_merge($deny_people, $deny_groups));
2892 $recipients = array_diff($recipients, $deny);
2896 public static function getFeedTags($item)
2900 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2902 for ($x = 0; $x < $cnt; $x ++) {
2903 if ($matches[1][$x]) {
2904 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2909 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2911 for ($x = 0; $x < $cnt; $x ++) {
2912 if ($matches[1][$x]) {
2913 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2920 public static function expire($uid, $days, $network = "", $force = false)
2922 if (!$uid || ($days < 1)) {
2926 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2927 $uid, GRAVITY_PARENT];
2930 * $expire_network_only = save your own wall posts
2931 * and just expire conversations started by others
2933 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2935 if ($expire_network_only) {
2936 $condition[0] .= " AND NOT `wall`";
2939 if ($network != "") {
2940 $condition[0] .= " AND `network` = ?";
2941 $condition[] = $network;
2944 * There is an index "uid_network_received" but not "uid_network_created"
2945 * This avoids the creation of another index just for one purpose.
2946 * And it doesn't really matter wether to look at "received" or "created"
2948 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2949 $condition[] = $days;
2951 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2952 $condition[] = $days;
2955 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2957 if (!DBA::isResult($items)) {
2961 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2963 // Forcing expiring of items - but not notes and marked items
2965 $expire_items = true;
2968 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2969 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2970 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2974 while ($item = Item::fetch($items)) {
2975 // don't expire filed items
2977 if (strpos($item['file'], '[') !== false) {
2981 // Only expire posts, not photos and photo comments
2983 if (!$expire_photos && strlen($item['resource-id'])) {
2985 } elseif (!$expire_starred && intval($item['starred'])) {
2987 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2989 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2993 self::deleteById($item['id'], PRIORITY_LOW);
2998 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3001 public static function firstPostDate($uid, $wall = false)
3003 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3004 $params = ['order' => ['created' => false]];
3005 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
3006 if (DBA::isResult($thread)) {
3007 return substr(DateTimeFormat::local($thread['created']), 0, 10);
3013 * @brief add/remove activity to an item
3015 * Toggle activities as like,dislike,attend of an item
3017 * @param string $item_id
3018 * @param string $verb
3019 * Activity verb. One of
3020 * like, unlike, dislike, undislike, attendyes, unattendyes,
3021 * attendno, unattendno, attendmaybe, unattendmaybe
3023 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3024 * @throws \ImagickException
3025 * @hook 'post_local_end'
3027 * 'post_id' => ID of posted item
3029 public static function performLike($item_id, $verb)
3031 if (!local_user() && !remote_user()) {
3038 $activity = ACTIVITY_LIKE;
3042 $activity = ACTIVITY_DISLIKE;
3046 $activity = ACTIVITY_ATTEND;
3050 $activity = ACTIVITY_ATTENDNO;
3053 case 'unattendmaybe':
3054 $activity = ACTIVITY_ATTENDMAYBE;
3057 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3061 // Enable activity toggling instead of on/off
3062 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3064 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3066 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3067 if (!DBA::isResult($item)) {
3068 Logger::log('like: unknown item ' . $item_id);
3072 $item_uri = $item['uri'];
3074 $uid = $item['uid'];
3075 if (($uid == 0) && local_user()) {
3076 $uid = local_user();
3079 if (!Security::canWriteToUserWall($uid)) {
3080 Logger::log('like: unable to write on wall ' . $uid);
3084 // Retrieves the local post owner
3085 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3086 if (!DBA::isResult($owner_self_contact)) {
3087 Logger::log('like: unknown owner ' . $uid);
3091 // Retrieve the current logged in user's public contact
3092 $author_id = public_contact();
3094 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3095 if (!DBA::isResult($author_contact)) {
3096 Logger::log('like: unknown author ' . $author_id);
3100 // Contact-id is the uid-dependant author contact
3101 if (local_user() == $uid) {
3102 $item_contact_id = $owner_self_contact['id'];
3104 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3105 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3106 if (!DBA::isResult($item_contact)) {
3107 Logger::log('like: unknown item contact ' . $item_contact_id);
3112 // Look for an existing verb row
3113 // event participation are essentially radio toggles. If you make a subsequent choice,
3114 // we need to eradicate your first choice.
3115 if ($event_verb_flag) {
3116 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3118 // Translate to the index based activity index
3120 foreach ($verbs as $verb) {
3121 $activities[] = self::activityToIndex($verb);
3124 $activities = self::activityToIndex($activity);
3127 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3128 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3130 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3132 // If it exists, mark it as deleted
3133 if (DBA::isResult($like_item)) {
3134 self::deleteById($like_item['id']);
3136 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3141 // Verb is "un-something", just trying to delete existing entries
3142 if (strpos($verb, 'un') === 0) {
3146 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3149 'guid' => System::createUUID(),
3150 'uri' => self::newURI($item['uid']),
3151 'uid' => $item['uid'],
3152 'contact-id' => $item_contact_id,
3153 'wall' => $item['wall'],
3155 'network' => Protocol::DFRN,
3156 'gravity' => GRAVITY_ACTIVITY,
3157 'parent' => $item['id'],
3158 'parent-uri' => $item['uri'],
3159 'thr-parent' => $item['uri'],
3160 'owner-id' => $author_id,
3161 'author-id' => $author_id,
3162 'body' => $activity,
3163 'verb' => $activity,
3164 'object-type' => $objtype,
3165 'allow_cid' => $item['allow_cid'],
3166 'allow_gid' => $item['allow_gid'],
3167 'deny_cid' => $item['deny_cid'],
3168 'deny_gid' => $item['deny_gid'],
3173 $signed = Diaspora::createLikeSignature($uid, $new_item);
3174 if (!empty($signed)) {
3175 $new_item['diaspora_signed_text'] = json_encode($signed);
3178 $new_item_id = self::insert($new_item);
3180 // If the parent item isn't visible then set it to visible
3181 if (!$item['visible']) {
3182 self::update(['visible' => true], ['id' => $item['id']]);
3185 $new_item['id'] = $new_item_id;
3187 Hook::callAll('post_local_end', $new_item);
3192 private static function addThread($itemid, $onlyshadow = false)
3194 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3195 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3196 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3197 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3198 $item = self::selectFirst($fields, $condition);
3200 if (!DBA::isResult($item)) {
3204 $item['iid'] = $itemid;
3207 $result = DBA::insert('thread', $item);
3209 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3213 private static function updateThread($itemid, $setmention = false)
3215 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3216 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3217 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3218 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3220 $item = self::selectFirst($fields, $condition);
3221 if (!DBA::isResult($item)) {
3226 $item["mention"] = 1;
3231 foreach ($item as $field => $data) {
3232 if (!in_array($field, ["guid"])) {
3233 $fields[$field] = $data;
3237 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3239 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3242 private static function deleteThread($itemid, $itemuri = "")
3244 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3245 if (!DBA::isResult($item)) {
3246 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3250 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3252 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3254 if ($itemuri != "") {
3255 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3256 if (!self::exists($condition)) {
3257 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3258 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3263 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3265 $local_user = local_user();
3266 $remote_user = remote_user();
3269 * Construct permissions
3271 * default permissions - anonymous user
3273 $sql = " AND NOT `item`.`private`";
3275 // Profile owner - everything is visible
3276 if ($local_user && ($local_user == $owner_id)) {
3278 } elseif ($remote_user) {
3280 * Authenticated visitor. Unless pre-verified,
3281 * check that the contact belongs to this $owner_id
3282 * and load the groups the visitor belongs to.
3283 * If pre-verified, the caller is expected to have already
3284 * done this and passed the groups into this function.
3286 $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3289 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3294 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3301 * get translated item type
3306 public static function postType($item)
3308 if (!empty($item['event-id'])) {
3309 return L10n::t('event');
3310 } elseif (!empty($item['resource-id'])) {
3311 return L10n::t('photo');
3312 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3313 return L10n::t('activity');
3314 } elseif ($item['id'] != $item['parent']) {
3315 return L10n::t('comment');
3318 return L10n::t('post');
3322 * Sets the "rendered-html" field of the provided item
3324 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3326 * @param array $item
3327 * @param bool $update
3329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3330 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3332 public static function putInCache(&$item, $update = false)
3334 $body = $item["body"];
3336 $rendered_hash = defaults($item, 'rendered-hash', '');
3337 $rendered_html = defaults($item, 'rendered-html', '');
3339 if ($rendered_hash == ''
3340 || $rendered_html == ""
3341 || $rendered_hash != hash("md5", $item["body"])
3342 || Config::get("system", "ignore_cache")
3344 $a = self::getApp();
3345 redir_private_images($a, $item);
3347 $item["rendered-html"] = prepare_text($item["body"]);
3348 $item["rendered-hash"] = hash("md5", $item["body"]);
3350 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3351 Hook::callAll('put_item_in_cache', $hook_data);
3352 $item['rendered-html'] = $hook_data['rendered-html'];
3353 $item['rendered-hash'] = $hook_data['rendered-hash'];
3356 // Force an update if the generated values differ from the existing ones
3357 if ($rendered_hash != $item["rendered-hash"]) {
3361 // Only compare the HTML when we forcefully ignore the cache
3362 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3366 if ($update && !empty($item["id"])) {
3369 'rendered-html' => $item["rendered-html"],
3370 'rendered-hash' => $item["rendered-hash"]
3372 ['id' => $item["id"]]
3377 $item["body"] = $body;
3381 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3382 * If attach is true, also add icons for item attachments.
3384 * @param array $item
3385 * @param boolean $attach
3386 * @param boolean $is_preview
3387 * @return string item body html
3388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3389 * @throws \ImagickException
3390 * @hook prepare_body_init item array before any work
3391 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3392 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3393 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3395 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3397 $a = self::getApp();
3398 Hook::callAll('prepare_body_init', $item);
3400 // In order to provide theme developers more possibilities, event items
3401 // are treated differently.
3402 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3403 $ev = Event::getItemHTML($item);
3407 $tags = Term::populateTagsFromItem($item);
3409 $item['tags'] = $tags['tags'];
3410 $item['hashtags'] = $tags['hashtags'];
3411 $item['mentions'] = $tags['mentions'];
3413 // Compile eventual content filter reasons
3414 $filter_reasons = [];
3415 if (!$is_preview && public_contact() != $item['author-id']) {
3416 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3417 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3422 'filter_reasons' => $filter_reasons
3424 Hook::callAll('prepare_body_content_filter', $hook_data);
3425 $filter_reasons = $hook_data['filter_reasons'];
3429 // Update the cached values if there is no "zrl=..." on the links.
3430 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3432 // Or update it if the current viewer is the intented viewer.
3433 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3437 self::putInCache($item, $update);
3438 $s = $item["rendered-html"];
3443 'preview' => $is_preview,
3444 'filter_reasons' => $filter_reasons
3446 Hook::callAll('prepare_body', $hook_data);
3447 $s = $hook_data['html'];
3451 // Replace the blockquotes with quotes that are used in mails.
3452 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3453 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3460 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3461 foreach ($matches as $mtch) {
3464 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3466 if (strpos($mime, 'video') !== false) {
3469 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3470 '$baseurl' => System::baseUrl(),
3474 $url_parts = explode('/', $the_url);
3475 $id = end($url_parts);
3476 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3479 'title' => L10n::t('View Video'),
3486 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3488 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3489 $filesubtype = str_replace('.', '-', $filesubtype);
3492 $filesubtype = 'unkn';
3495 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3496 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3498 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3499 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3503 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3507 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3508 $x = Map::byCoordinates(trim($item['coord']));
3510 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3515 // Look for spoiler.
3516 $spoilersearch = '<blockquote class="spoiler">';
3518 // Remove line breaks before the spoiler.
3519 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3520 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3522 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3523 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3526 while ((strpos($s, $spoilersearch) !== false)) {
3527 $pos = strpos($s, $spoilersearch);
3528 $rnd = Strings::getRandomHex(8);
3529 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3530 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3531 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3534 // Look for quote with author.
3535 $authorsearch = '<blockquote class="author">';
3537 while ((strpos($s, $authorsearch) !== false)) {
3538 $pos = strpos($s, $authorsearch);
3539 $rnd = Strings::getRandomHex(8);
3540 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3541 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3542 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3545 // Replace friendica image url size with theme preference.
3546 if (!empty($a->theme_info['item_image_size'])) {
3547 $ps = $a->theme_info['item_image_size'];
3548 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3551 $s = HTML::applyContentFilter($s, $filter_reasons);
3553 $hook_data = ['item' => $item, 'html' => $s];
3554 Hook::callAll('prepare_body_final', $hook_data);
3556 return $hook_data['html'];
3560 * get private link for item
3562 * @param array $item
3563 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3564 * @throws \Exception
3566 public static function getPlink($item)
3568 $a = self::getApp();
3570 if ($a->user['nickname'] != "") {
3572 'href' => "display/" . $item['guid'],
3573 'orig' => "display/" . $item['guid'],
3574 'title' => L10n::t('View on separate page'),
3575 'orig_title' => L10n::t('view on separate page'),
3578 if (!empty($item['plink'])) {
3579 $ret["href"] = $a->removeBaseURL($item['plink']);
3580 $ret["title"] = L10n::t('link to source');
3583 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3585 'href' => $item['plink'],
3586 'orig' => $item['plink'],
3587 'title' => L10n::t('link to source'),
3597 * Is the given item array a post that is sent as starting post to a forum?
3599 * @param array $item
3600 * @param array $owner
3602 * @return boolean "true" when it is a forum post
3604 public static function isForumPost(array $item, array $owner = [])
3606 if (empty($owner)) {
3607 $owner = User::getOwnerDataById($item['uid']);
3608 if (empty($owner)) {
3613 if (($item['author-id'] == $item['owner-id']) ||
3614 ($owner['id'] == $item['contact-id']) ||
3615 ($item['uri'] != $item['parent-uri']) ||
3620 return Contact::isForum($item['contact-id']);