4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\Lock;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\PermissionSet;
21 use Friendica\Model\ItemURI;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use Text_LanguageDetect;
29 require_once 'boot.php';
30 require_once 'include/items.php';
31 require_once 'include/text.php';
33 class Item extends BaseObject
35 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
42 const PT_DOCUMENT = 19;
44 const PT_PERSONAL_NOTE = 128;
46 // Field list that is used to display the items
47 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
48 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
49 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
50 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
51 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
52 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
53 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
54 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
55 'writable', 'self', 'cid', 'alias',
56 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
57 'event-summary', 'event-desc', 'event-location', 'event-type',
58 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
60 // Field list that is used to deliver items via the protocols
61 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
62 'created', 'edited', 'verb', 'object-type', 'object', 'target',
63 'private', 'title', 'body', 'location', 'coord', 'app',
64 'attach', 'tag', 'deleted', 'extid', 'post-type',
65 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
66 'author-id', 'author-link', 'owner-link', 'contact-uid',
67 'signed_text', 'signature', 'signer', 'network'];
69 // Field list for "item-content" table that is mixed with the item table
70 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
71 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
72 'object-type', 'object', 'target-type', 'target', 'plink'];
74 // Field list for "item-content" table that is not present in the "item" table
75 const CONTENT_FIELDLIST = ['language'];
77 // Field list for additional delivery data
78 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
80 // All fields in the item table
81 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
82 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
83 'uri-hash', 'created', 'edited', 'commented', 'received', 'changed', 'verb',
84 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
85 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
86 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
87 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
88 'title', 'content-warning', 'body', 'location', 'coord', 'app',
89 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
90 'author-id', 'author-link', 'author-name', 'author-avatar',
91 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
93 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
94 // The item-activity table only stores the index and needs this array to know the matching activity.
95 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
97 private static $legacy_mode = null;
99 public static function isLegacyMode()
101 if (is_null(self::$legacy_mode)) {
102 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
105 return self::$legacy_mode;
109 * @brief returns an activity index from an activity string
111 * @param string $activity activity string
112 * @return integer Activity index
114 public static function activityToIndex($activity)
116 $index = array_search($activity, self::ACTIVITIES);
118 if (is_bool($index)) {
126 * @brief returns an activity string from an activity index
128 * @param integer $index activity index
129 * @return string Activity string
131 private static function indexToActivity($index)
133 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
137 return self::ACTIVITIES[$index];
141 * @brief Fetch a single item row
143 * @param mixed $stmt statement object
144 * @return array current row
146 public static function fetch($stmt)
148 $row = DBA::fetch($stmt);
154 // ---------------------- Transform item structure data ----------------------
156 // We prefer the data from the user's contact over the public one
157 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
158 ($row['author-link'] == $row['contact-link'])) {
159 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
160 $row['author-avatar'] = $row['contact-avatar'];
162 if (isset($row['author-name']) && !empty($row['contact-name'])) {
163 $row['author-name'] = $row['contact-name'];
167 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
168 ($row['owner-link'] == $row['contact-link'])) {
169 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
170 $row['owner-avatar'] = $row['contact-avatar'];
172 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
173 $row['owner-name'] = $row['contact-name'];
177 // We can always comment on posts from these networks
178 if (array_key_exists('writable', $row) &&
179 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
180 $row['writable'] = true;
183 // ---------------------- Transform item content data ----------------------
185 // Fetch data from the item-content table whenever there is content there
186 if (self::isLegacyMode()) {
187 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
188 foreach ($legacy_fields as $field) {
189 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
190 $row[$field] = $row['internal-item-' . $field];
192 unset($row['internal-item-' . $field]);
196 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
197 $row['verb'] = self::indexToActivity($row['internal-activity']);
198 if (array_key_exists('title', $row)) {
201 if (array_key_exists('body', $row)) {
202 $row['body'] = $row['verb'];
204 if (array_key_exists('object', $row)) {
207 if (array_key_exists('object-type', $row)) {
208 $row['object-type'] = ACTIVITY_OBJ_NOTE;
210 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
211 // Posts don't have an object or target - but having tags or files.
212 // We safe some performance by building tag and file strings only here.
213 // We remove object and target since they aren't used for this type.
214 if (array_key_exists('object', $row)) {
217 if (array_key_exists('target', $row)) {
222 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
223 // Build the tag string out of the term entries
224 if (array_key_exists('tag', $row) && empty($row['tag'])) {
225 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
228 // Build the file string out of the term entries
229 if (array_key_exists('file', $row) && empty($row['file'])) {
230 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
234 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
235 $row['ignored'] = $row['internal-user-ignored'];
238 // Remove internal fields
239 unset($row['internal-activity']);
240 unset($row['internal-network']);
241 unset($row['internal-iid']);
242 unset($row['internal-iaid']);
243 unset($row['internal-icid']);
244 unset($row['internal-user-ignored']);
250 * @brief Fills an array with data from an item query
252 * @param object $stmt statement object
253 * @return array Data array
255 public static function inArray($stmt, $do_close = true) {
256 if (is_bool($stmt)) {
261 while ($row = self::fetch($stmt)) {
271 * @brief Check if item data exists
273 * @param array $condition array of fields for condition
275 * @return boolean Are there rows for that condition?
277 public static function exists($condition) {
278 $stmt = self::select(['id'], $condition, ['limit' => 1]);
280 if (is_bool($stmt)) {
283 $retval = (DBA::numRows($stmt) > 0);
292 * Retrieve a single record from the item table for a given user and returns it in an associative array
294 * @brief Retrieve a single record from a table
295 * @param integer $uid User ID
296 * @param array $fields
297 * @param array $condition
298 * @param array $params
302 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
304 $params['uid'] = $uid;
306 if (empty($selected)) {
307 $selected = Item::DISPLAY_FIELDLIST;
310 return self::selectFirst($selected, $condition, $params);
314 * @brief Select rows from the item table for a given user
316 * @param integer $uid User ID
317 * @param array $selected Array of selected fields, empty for all
318 * @param array $condition Array of fields for condition
319 * @param array $params Array of several parameters
321 * @return boolean|object
323 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
325 $params['uid'] = $uid;
327 if (empty($selected)) {
328 $selected = Item::DISPLAY_FIELDLIST;
331 return self::select($selected, $condition, $params);
335 * Retrieve a single record from the item table and returns it in an associative array
337 * @brief Retrieve a single record from a table
338 * @param array $fields
339 * @param array $condition
340 * @param array $params
344 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
346 $params['limit'] = 1;
348 $result = self::select($fields, $condition, $params);
350 if (is_bool($result)) {
353 $row = self::fetch($result);
360 * @brief Select rows from the item table
362 * @param array $selected Array of selected fields, empty for all
363 * @param array $condition Array of fields for condition
364 * @param array $params Array of several parameters
366 * @return boolean|object
368 public static function select(array $selected = [], array $condition = [], $params = [])
373 if (isset($params['uid'])) {
374 $uid = $params['uid'];
378 $fields = self::fieldlist($selected, $usermode);
380 $select_fields = self::constructSelectFields($fields, $selected);
382 $condition_string = DBA::buildCondition($condition);
384 $condition_string = self::addTablesToFields($condition_string, $fields);
387 $condition_string = $condition_string . ' AND ' . self::condition(false);
390 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
392 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
394 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
396 return DBA::p($sql, $condition);
400 * @brief Select rows from the starting post in the item table
402 * @param integer $uid User ID
403 * @param array $fields Array of selected fields, empty for all
404 * @param array $condition Array of fields for condition
405 * @param array $params Array of several parameters
407 * @return boolean|object
409 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
411 $params['uid'] = $uid;
413 if (empty($selected)) {
414 $selected = Item::DISPLAY_FIELDLIST;
417 return self::selectThread($selected, $condition, $params);
421 * Retrieve a single record from the starting post in the item table and returns it in an associative array
423 * @brief Retrieve a single record from a table
424 * @param integer $uid User ID
425 * @param array $selected
426 * @param array $condition
427 * @param array $params
431 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
433 $params['uid'] = $uid;
435 if (empty($selected)) {
436 $selected = Item::DISPLAY_FIELDLIST;
439 return self::selectFirstThread($selected, $condition, $params);
443 * Retrieve a single record from the starting post in the item table and returns it in an associative array
445 * @brief Retrieve a single record from a table
446 * @param array $fields
447 * @param array $condition
448 * @param array $params
452 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
454 $params['limit'] = 1;
455 $result = self::selectThread($fields, $condition, $params);
457 if (is_bool($result)) {
460 $row = self::fetch($result);
467 * @brief Select rows from the starting post in the item table
469 * @param array $selected Array of selected fields, empty for all
470 * @param array $condition Array of fields for condition
471 * @param array $params Array of several parameters
473 * @return boolean|object
475 public static function selectThread(array $selected = [], array $condition = [], $params = [])
480 if (isset($params['uid'])) {
481 $uid = $params['uid'];
485 $fields = self::fieldlist($selected, $usermode);
487 $fields['thread'] = ['mention', 'ignored', 'iid'];
489 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
490 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
491 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
492 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
494 $select_fields = self::constructSelectFields($fields, $selected);
496 $condition_string = DBA::buildCondition($condition);
498 $condition_string = self::addTablesToFields($condition_string, $threadfields);
499 $condition_string = self::addTablesToFields($condition_string, $fields);
502 $condition_string = $condition_string . ' AND ' . self::condition(true);
505 $param_string = DBA::buildParameter($params);
506 $param_string = self::addTablesToFields($param_string, $threadfields);
507 $param_string = self::addTablesToFields($param_string, $fields);
509 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
511 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
513 return DBA::p($sql, $condition);
517 * @brief Returns a list of fields that are associated with the item table
519 * @return array field list
521 private static function fieldlist($selected, $usermode)
525 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
526 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
527 'created', 'edited', 'commented', 'received', 'changed', 'psid', 'uri-hash',
528 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
529 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
530 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
531 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
532 'network' => 'internal-network', 'icid' => 'internal-icid',
533 'iaid' => 'internal-iaid'];
536 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
539 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
541 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
543 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
545 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
547 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
548 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
550 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
551 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
553 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
554 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
555 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
557 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
559 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
561 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
562 'start' => 'event-start','finish' => 'event-finish',
563 'summary' => 'event-summary','desc' => 'event-desc',
564 'location' => 'event-location', 'type' => 'event-type',
565 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
566 'ignore' => 'event-ignore', 'id' => 'event-id'];
568 $fields['sign'] = ['signed_text', 'signature', 'signer'];
574 * @brief Returns SQL condition for the "select" functions
576 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
578 * @return string SQL condition
580 private static function condition($thread_mode)
583 $master_table = "`thread`";
585 $master_table = "`item`";
587 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
588 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
589 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
590 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
591 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
592 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
593 GRAVITY_PARENT, GRAVITY_PARENT);
597 * @brief Returns all needed "JOIN" commands for the "select" functions
599 * @param integer $uid User ID
600 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
601 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
603 * @return string The SQL joins for the "select" functions
605 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
608 $master_table = "`thread`";
609 $master_table_key = "`thread`.`iid`";
610 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
612 $master_table = "`item`";
613 $master_table_key = "`item`.`id`";
618 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
619 AND NOT `contact`.`blocked`
620 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
621 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
622 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
623 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
624 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
625 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
626 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
627 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
629 if (strpos($sql_commands, "`contact`.") !== false) {
630 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
632 if (strpos($sql_commands, "`author`.") !== false) {
633 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
635 if (strpos($sql_commands, "`owner`.") !== false) {
636 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
640 if (strpos($sql_commands, "`group_member`.") !== false) {
641 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
644 if (strpos($sql_commands, "`user`.") !== false) {
645 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
648 if (strpos($sql_commands, "`event`.") !== false) {
649 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
652 if (strpos($sql_commands, "`sign`.") !== false) {
653 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
656 if (strpos($sql_commands, "`item-activity`.") !== false) {
657 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
660 if (strpos($sql_commands, "`item-content`.") !== false) {
661 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
664 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
665 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
668 if (strpos($sql_commands, "`permissionset`.") !== false) {
669 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
672 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
673 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
676 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
677 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
684 * @brief Add the field list for the "select" functions
686 * @param array $fields The field definition array
687 * @param array $selected The array with the selected fields from the "select" functions
689 * @return string The field list
691 private static function constructSelectFields($fields, $selected)
693 if (!empty($selected)) {
694 $selected[] = 'internal-iid';
695 $selected[] = 'internal-iaid';
696 $selected[] = 'internal-icid';
697 $selected[] = 'internal-network';
700 if (in_array('verb', $selected)) {
701 $selected[] = 'internal-activity';
704 if (in_array('ignored', $selected)) {
705 $selected[] = 'internal-user-ignored';
709 foreach ($fields as $table => $table_fields) {
710 foreach ($table_fields as $field => $select) {
711 if (empty($selected) || in_array($select, $selected)) {
712 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
713 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
714 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
716 if (is_int($field)) {
717 $selection[] = "`" . $table . "`.`" . $select . "`";
719 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
724 return implode(", ", $selection);
728 * @brief add table definition to fields in an SQL query
730 * @param string $query SQL query
731 * @param array $fields The field definition array
733 * @return string the changed SQL query
735 private static function addTablesToFields($query, $fields)
737 foreach ($fields as $table => $table_fields) {
738 foreach ($table_fields as $alias => $field) {
739 if (is_int($alias)) {
740 $replace_field = $field;
742 $replace_field = $alias;
745 $search = "/([^\.])`" . $field . "`/i";
746 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
747 $query = preg_replace($search, $replace, $query);
754 * @brief Generate a server unique item hash for linking between the item tables
756 * @param string $uri Item URI
757 * @param date $created Item creation date
759 * @return string the item hash
761 private static function itemHash($uri, $created)
763 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
767 * @brief Update existing item entries
769 * @param array $fields The fields that are to be changed
770 * @param array $condition The condition for finding the item entries
772 * In the future we may have to change permissions as well.
773 * Then we had to add the user id as third parameter.
775 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
777 * @return integer|boolean number of affected rows - or "false" if there was an error
779 public static function update(array $fields, array $condition)
781 if (empty($condition) || empty($fields)) {
785 // To ensure the data integrity we do it in an transaction
788 // We cannot simply expand the condition to check for origin entries
789 // The condition needn't to be a simple array but could be a complex condition.
790 // And we have to execute this query before the update to ensure to fetch the same data.
791 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
793 $content_fields = [];
794 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
795 if (isset($fields[$field])) {
796 $content_fields[$field] = $fields[$field];
797 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
798 unset($fields[$field]);
800 $fields[$field] = null;
805 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
806 foreach ($clear_fields as $field) {
807 if (array_key_exists($field, $fields)) {
808 $fields[$field] = null;
812 if (array_key_exists('tag', $fields)) {
813 $tags = $fields['tag'];
814 $fields['tag'] = null;
819 if (array_key_exists('file', $fields)) {
820 $files = $fields['file'];
821 $fields['file'] = null;
826 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
827 'inform' => defaults($fields, 'inform', '')];
829 $fields['postopts'] = null;
830 $fields['inform'] = null;
832 if (!empty($fields)) {
833 $success = DBA::update('item', $fields, $condition);
842 // When there is no content for the "old" item table, this will count the fetched items
843 $rows = DBA::affectedRows();
845 while ($item = DBA::fetch($items)) {
847 // This part here can safely be removed when the legacy fields in the item had been removed
848 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
850 // Fetch the uri-hash from an existing item entry if there is one
851 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
852 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
853 if (DBA::isResult($existing)) {
854 $item['uri-hash'] = $existing['uri-hash'];
856 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
859 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
860 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
861 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
864 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
865 if (!empty($item['iaid'])) {
866 $update_condition = ['id' => $item['iaid']];
868 $update_condition = ['uri-hash' => $item['uri-hash']];
870 self::updateActivity($content_fields, $update_condition);
872 if (empty($item['iaid'])) {
873 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
874 if (DBA::isResult($item_activity)) {
875 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
876 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
877 if (self::isLegacyMode()) {
878 $item_fields[$field] = null;
880 unset($item_fields[$field]);
883 DBA::update('item', $item_fields, ['id' => $item['id']]);
885 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
886 DBA::delete('item-content', ['id' => $item['icid']]);
889 } elseif (!empty($item['icid'])) {
890 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
892 if (!DBA::exists('item', ['icid' => $item['icid']])) {
893 DBA::delete('item-content', ['id' => $item['icid']]);
897 if (!empty($item['icid'])) {
898 $update_condition = ['id' => $item['icid']];
900 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
902 self::updateContent($content_fields, $update_condition);
904 if (empty($item['icid'])) {
905 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
906 if (DBA::isResult($item_content)) {
907 $item_fields = ['icid' => $item_content['id']];
908 // Clear all fields in the item table that have a content in the item-content table
909 foreach ($item_content as $field => $content) {
910 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
911 if (self::isLegacyMode()) {
912 $item_fields[$field] = null;
914 unset($item_fields[$field]);
918 DBA::update('item', $item_fields, ['id' => $item['id']]);
924 Term::insertFromTagFieldByItemId($item['id'], $tags);
925 if (!empty($item['tag'])) {
926 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
930 if (!empty($files)) {
931 Term::insertFromFileFieldByItemId($item['id'], $files);
932 if (!empty($item['file'])) {
933 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
937 self::updateDeliveryData($item['id'], $delivery_data);
939 self::updateThread($item['id']);
941 // We only need to notfiy others when it is an original entry from us.
942 // Only call the notifier when the item has some content relevant change.
943 if ($item['origin'] && in_array('edited', array_keys($fields))) {
944 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
954 * @brief Delete an item and notify others about it - if it was ours
956 * @param array $condition The condition for finding the item entries
957 * @param integer $priority Priority for the notification
959 public static function delete($condition, $priority = PRIORITY_HIGH)
961 $items = self::select(['id'], $condition);
962 while ($item = self::fetch($items)) {
963 self::deleteById($item['id'], $priority);
969 * @brief Delete an item for an user and notify others about it - if it was ours
971 * @param array $condition The condition for finding the item entries
972 * @param integer $uid User who wants to delete this item
974 public static function deleteForUser($condition, $uid)
980 $items = self::select(['id', 'uid'], $condition);
981 while ($item = self::fetch($items)) {
982 // "Deleting" global items just means hiding them
983 if ($item['uid'] == 0) {
984 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
985 } elseif ($item['uid'] == $uid) {
986 self::deleteById($item['id'], PRIORITY_HIGH);
988 logger('Wrong ownership. Not deleting item ' . $item['id']);
995 * @brief Delete an item and notify others about it - if it was ours
997 * @param integer $item_id Item ID that should be delete
998 * @param integer $priority Priority for the notification
1000 * @return boolean success
1002 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
1004 // locate item to be deleted
1005 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1006 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1007 'verb', 'object-type', 'object', 'target', 'contact-id',
1008 'icid', 'iaid', 'psid'];
1009 $item = self::selectFirst($fields, ['id' => $item_id]);
1010 if (!DBA::isResult($item)) {
1011 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
1015 if ($item['deleted']) {
1016 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
1020 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1021 if (!DBA::isResult($parent)) {
1022 $parent = ['origin' => false];
1025 // clean up categories and tags so they don't end up as orphans
1028 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1030 foreach ($matches as $mtch) {
1031 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1037 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1039 foreach ($matches as $mtch) {
1040 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1045 * If item is a link to a photo resource, nuke all the associated photos
1046 * (visitors will not have photo resources)
1047 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1048 * generate a resource-id and therefore aren't intimately linked to the item.
1050 if (strlen($item['resource-id'])) {
1051 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1054 // If item is a link to an event, delete the event.
1055 if (intval($item['event-id'])) {
1056 Event::delete($item['event-id']);
1059 // If item has attachments, drop them
1060 foreach (explode(", ", $item['attach']) as $attach) {
1061 preg_match("|attach/(\d+)|", $attach, $matches);
1062 if (is_array($matches) && count($matches) > 1) {
1063 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1067 // Delete tags that had been attached to other items
1068 self::deleteTagsFromItem($item);
1070 // Set the item to "deleted"
1071 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1072 DBA::update('item', $item_fields, ['id' => $item['id']]);
1074 Term::insertFromTagFieldByItemId($item['id'], '');
1075 Term::insertFromFileFieldByItemId($item['id'], '');
1076 self::deleteThread($item['id'], $item['parent-uri']);
1078 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1079 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1082 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1084 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1086 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1087 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1089 // When the permission set will be used in photo and events as well,
1090 // this query here needs to be extended.
1091 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1092 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1095 // If it's the parent of a comment thread, kill all the kids
1096 if ($item['id'] == $item['parent']) {
1097 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1100 // Is it our comment and/or our thread?
1101 if ($item['origin'] || $parent['origin']) {
1103 // When we delete the original post we will delete all existing copies on the server as well
1104 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1106 // send the notification upstream/downstream
1107 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1108 } elseif ($item['uid'] != 0) {
1110 // When we delete just our local user copy of an item, we have to set a marker to hide it
1111 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1112 if (DBA::isResult($global_item)) {
1113 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1117 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1122 private static function deleteTagsFromItem($item)
1124 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1128 $xo = XML::parseString($item["object"], false);
1129 $xt = XML::parseString($item["target"], false);
1131 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1135 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1136 if (!DBA::isResult($i)) {
1140 // For tags, the owner cannot remove the tag on the author's copy of the post.
1141 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1142 $author_copy = $item["origin"];
1144 if (($owner_remove && $author_copy) || !$owner_remove) {
1148 $tags = explode(',', $i["tag"]);
1151 foreach ($tags as $tag) {
1152 if (trim($tag) !== trim($xo->body)) {
1153 $newtags[] = trim($tag);
1157 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1160 private static function guid($item, $notify)
1162 if (!empty($item['guid'])) {
1163 return notags(trim($item['guid']));
1167 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1168 // We add the hash of our own host because our host is the original creator of the post.
1169 $prefix_host = get_app()->getHostName();
1173 // We are only storing the post so we create a GUID from the original hostname.
1174 if (!empty($item['author-link'])) {
1175 $parsed = parse_url($item['author-link']);
1176 if (!empty($parsed['host'])) {
1177 $prefix_host = $parsed['host'];
1181 if (empty($prefix_host) && !empty($item['plink'])) {
1182 $parsed = parse_url($item['plink']);
1183 if (!empty($parsed['host'])) {
1184 $prefix_host = $parsed['host'];
1188 if (empty($prefix_host) && !empty($item['uri'])) {
1189 $parsed = parse_url($item['uri']);
1190 if (!empty($parsed['host'])) {
1191 $prefix_host = $parsed['host'];
1195 // Is it in the format data@host.tld? - Used for mail contacts
1196 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1197 $mailparts = explode('@', $item['author-link']);
1198 $prefix_host = array_pop($mailparts);
1202 if (!empty($item['plink'])) {
1203 $guid = self::guidFromUri($item['plink'], $prefix_host);
1204 } elseif (!empty($item['uri'])) {
1205 $guid = self::guidFromUri($item['uri'], $prefix_host);
1207 $guid = System::createUUID(hash('crc32', $prefix_host));
1213 private static function contactId($item)
1215 $contact_id = (int)$item["contact-id"];
1217 if (!empty($contact_id)) {
1220 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1222 * First we are looking for a suitable contact that matches with the author of the post
1223 * This is done only for comments
1225 if ($item['parent-uri'] != $item['uri']) {
1226 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1229 // If not present then maybe the owner was found
1230 if ($contact_id == 0) {
1231 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1234 // Still missing? Then use the "self" contact of the current user
1235 if ($contact_id == 0) {
1236 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1237 if (DBA::isResult($self)) {
1238 $contact_id = $self["id"];
1241 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1246 // This function will finally cover most of the preparation functionality in mod/item.php
1247 public static function prepare(&$item)
1249 $data = BBCode::getAttachmentData($item['body']);
1250 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1251 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1252 $posttype = Item::PT_PAGE;
1253 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1257 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1261 // If it is a posting where users should get notifications, then define it as wall posting
1264 $item['origin'] = 1;
1265 $item['network'] = Protocol::DFRN;
1266 $item['protocol'] = Conversation::PARCEL_DFRN;
1268 if (is_int($notify)) {
1269 $priority = $notify;
1271 $priority = PRIORITY_HIGH;
1274 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1277 $item['guid'] = self::guid($item, $notify);
1278 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1281 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1283 // Store conversation data
1284 $item = Conversation::insert($item);
1287 * If a Diaspora signature structure was passed in, pull it out of the
1288 * item array and set it aside for later storage.
1292 if (isset($item['dsprsig'])) {
1293 $encoded_signature = $item['dsprsig'];
1294 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1295 unset($item['dsprsig']);
1298 $diaspora_signed_text = '';
1299 if (isset($item['diaspora_signed_text'])) {
1300 $diaspora_signed_text = $item['diaspora_signed_text'];
1301 unset($item['diaspora_signed_text']);
1304 // Converting the plink
1305 /// @TODO Check if this is really still needed
1306 if ($item['network'] == Protocol::OSTATUS) {
1307 if (isset($item['plink'])) {
1308 $item['plink'] = OStatus::convertHref($item['plink']);
1309 } elseif (isset($item['uri'])) {
1310 $item['plink'] = OStatus::convertHref($item['uri']);
1314 if (!empty($item['thr-parent'])) {
1315 $item['parent-uri'] = $item['thr-parent'];
1318 if (isset($item['gravity'])) {
1319 $item['gravity'] = intval($item['gravity']);
1320 } elseif ($item['parent-uri'] === $item['uri']) {
1321 $item['gravity'] = GRAVITY_PARENT;
1322 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1323 $item['gravity'] = GRAVITY_COMMENT;
1325 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1326 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1329 $uid = intval($item['uid']);
1331 // check for create date and expire time
1332 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1334 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1335 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1336 $expire_interval = $user['expire'];
1339 if (($expire_interval > 0) && !empty($item['created'])) {
1340 $expire_date = time() - ($expire_interval * 86400);
1341 $created_date = strtotime($item['created']);
1342 if ($created_date < $expire_date) {
1343 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1349 * Do we already have this item?
1350 * We have to check several networks since Friendica posts could be repeated
1351 * via OStatus (maybe Diasporsa as well)
1353 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1354 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1355 trim($item['uri']), $item['uid'],
1356 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1357 $existing = self::selectFirst(['id', 'network'], $condition);
1358 if (DBA::isResult($existing)) {
1359 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1361 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1364 return $existing["id"];
1368 // Ensure to always have the same creation date.
1369 $existing = self::selectfirst(['created', 'uri-hash'], ['uri' => $item['uri']]);
1370 if (DBA::isResult($existing)) {
1371 $item['created'] = $existing['created'];
1372 $item['uri-hash'] = $existing['uri-hash'];
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'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1384 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1385 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1386 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1387 $item['commented'] = ((x($item, 'commented') !== false) ? 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'] = ((x($item, 'visible') !== false) ? 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 // Unique identifier to be linked against item-activities and item-content
1418 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1420 // When there is no content then we don't post it
1421 if ($item['body'].$item['title'] == '') {
1422 logger('No body, no title.');
1426 self::addLanguageToItemArray($item);
1428 // Items cannot be stored before they happen ...
1429 if ($item['created'] > DateTimeFormat::utcNow()) {
1430 $item['created'] = DateTimeFormat::utcNow();
1433 // We haven't invented time travel by now.
1434 if ($item['edited'] > DateTimeFormat::utcNow()) {
1435 $item['edited'] = DateTimeFormat::utcNow();
1438 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1440 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1441 $item["contact-id"] = self::contactId($item);
1443 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1444 'photo' => $item['author-avatar'], 'network' => $item['network']];
1446 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1448 if (Contact::isBlocked($item["author-id"])) {
1449 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1453 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1454 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1456 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1458 if (Contact::isBlocked($item["owner-id"])) {
1459 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1463 if ($item['network'] == Protocol::PHANTOM) {
1464 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1466 $item['network'] = Protocol::DFRN;
1467 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1470 // Checking if there is already an item with the same guid
1471 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1472 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1473 if (self::exists($condition)) {
1474 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1478 // Check for hashtags in the body and repair or add hashtag links
1479 self::setHashtags($item);
1481 $item['thr-parent'] = $item['parent-uri'];
1489 if ($item['parent-uri'] === $item['uri']) {
1490 $diaspora_signed_text = '';
1492 $parent_deleted = 0;
1493 $allow_cid = $item['allow_cid'];
1494 $allow_gid = $item['allow_gid'];
1495 $deny_cid = $item['deny_cid'];
1496 $deny_gid = $item['deny_gid'];
1497 $notify_type = 'wall-new';
1499 // find the parent and snarf the item id and ACLs
1500 // and anything else we need to inherit
1502 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1503 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1504 'wall', 'private', 'forum_mode', 'origin'];
1505 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1506 $params = ['order' => ['id' => false]];
1507 $parent = self::selectFirst($fields, $condition, $params);
1509 if (DBA::isResult($parent)) {
1510 // is the new message multi-level threaded?
1511 // even though we don't support it now, preserve the info
1512 // and re-attach to the conversation parent.
1514 if ($parent['uri'] != $parent['parent-uri']) {
1515 $item['parent-uri'] = $parent['parent-uri'];
1517 $condition = ['uri' => $item['parent-uri'],
1518 'parent-uri' => $item['parent-uri'],
1519 'uid' => $item['uid']];
1520 $params = ['order' => ['id' => false]];
1521 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1523 if (DBA::isResult($toplevel_parent)) {
1524 $parent = $toplevel_parent;
1528 $parent_id = $parent['id'];
1529 $parent_deleted = $parent['deleted'];
1530 $allow_cid = $parent['allow_cid'];
1531 $allow_gid = $parent['allow_gid'];
1532 $deny_cid = $parent['deny_cid'];
1533 $deny_gid = $parent['deny_gid'];
1534 $item['wall'] = $parent['wall'];
1535 $notify_type = 'comment-new';
1537 if (!$parent['origin']) {
1538 $diaspora_signed_text = '';
1542 * If the parent is private, force privacy for the entire conversation
1543 * This differs from the above settings as it subtly allows comments from
1544 * email correspondents to be private even if the overall thread is not.
1546 if ($parent['private']) {
1547 $item['private'] = $parent['private'];
1551 * Edge case. We host a public forum that was originally posted to privately.
1552 * The original author commented, but as this is a comment, the permissions
1553 * weren't fixed up so it will still show the comment as private unless we fix it here.
1555 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1556 $item['private'] = 0;
1559 // If its a post from myself then tag the thread as "mention"
1560 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1561 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1562 if (DBA::isResult($user)) {
1563 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1564 $self_id = Contact::getIdForURL($self, 0, true);
1565 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1566 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1567 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1568 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1573 * Allow one to see reply tweets from status.net even when
1574 * we don't have or can't see the original post.
1576 if ($force_parent) {
1577 logger('$force_parent=true, reply converted to top-level post.');
1579 $item['parent-uri'] = $item['uri'];
1580 $item['gravity'] = GRAVITY_PARENT;
1581 $diaspora_signed_text = '';
1583 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1587 $parent_deleted = 0;
1591 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1592 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1594 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1595 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1596 if (self::exists($condition)) {
1597 logger('duplicated item with the same uri found. '.print_r($item,true));
1601 // On Friendica and Diaspora the GUID is unique
1602 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1603 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1604 if (self::exists($condition)) {
1605 logger('duplicated item with the same guid found. '.print_r($item,true));
1609 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1610 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1611 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1612 if (self::exists($condition)) {
1613 logger('duplicated item with the same body found. '.print_r($item,true));
1618 // Is this item available in the global items (with uid=0)?
1619 if ($item["uid"] == 0) {
1620 $item["global"] = true;
1622 // Set the global flag on all items if this was a global item entry
1623 self::update(['global' => true], ['uri' => $item["uri"]]);
1625 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1629 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1632 $private = $item['private'];
1635 $item["allow_cid"] = $allow_cid;
1636 $item["allow_gid"] = $allow_gid;
1637 $item["deny_cid"] = $deny_cid;
1638 $item["deny_gid"] = $deny_gid;
1639 $item["private"] = $private;
1640 $item["deleted"] = $parent_deleted;
1642 // Fill the cache field
1643 put_item_in_cache($item);
1646 $item['edit'] = false;
1647 $item['parent'] = $parent_id;
1648 Addon::callHooks('post_local', $item);
1649 unset($item['edit']);
1650 unset($item['parent']);
1652 Addon::callHooks('post_remote', $item);
1655 // This array field is used to trigger some automatic reactions
1656 // It is mainly used in the "post_local" hook.
1657 unset($item['api_source']);
1659 if (x($item, 'cancel')) {
1660 logger('post cancelled by addon.');
1665 * Check for already added items.
1666 * There is a timing issue here that sometimes creates double postings.
1667 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1669 if ($item["uid"] == 0) {
1670 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1671 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1676 logger('' . print_r($item,true), LOGGER_DATA);
1678 if (array_key_exists('tag', $item)) {
1679 $tags = $item['tag'];
1680 unset($item['tag']);
1685 if (array_key_exists('file', $item)) {
1686 $files = $item['file'];
1687 unset($item['file']);
1692 // Creates or assigns the permission set
1693 $item['psid'] = PermissionSet::fetchIDForPost($item);
1695 // We are doing this outside of the transaction to avoid timing problems
1696 if (!self::insertActivity($item)) {
1697 self::insertContent($item);
1700 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1701 'inform' => defaults($item, 'inform', '')];
1703 unset($item['postopts']);
1704 unset($item['inform']);
1706 // These fields aren't stored anymore in the item table, they are fetched upon request
1707 unset($item['author-link']);
1708 unset($item['author-name']);
1709 unset($item['author-avatar']);
1711 unset($item['owner-link']);
1712 unset($item['owner-name']);
1713 unset($item['owner-avatar']);
1716 $ret = DBA::insert('item', $item);
1718 // When the item was successfully stored we fetch the ID of the item.
1719 if (DBA::isResult($ret)) {
1720 $current_post = DBA::lastInsertId();
1722 // This can happen - for example - if there are locking timeouts.
1725 // Store the data into a spool file so that we can try again later.
1727 // At first we restore the Diaspora signature that we removed above.
1728 if (isset($encoded_signature)) {
1729 $item['dsprsig'] = $encoded_signature;
1732 // Now we store the data in the spool directory
1733 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1734 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1736 $spoolpath = get_spoolpath();
1737 if ($spoolpath != "") {
1738 $spool = $spoolpath.'/'.$file;
1740 // Ensure to have the removed data from above again in the item array
1741 $item = array_merge($item, $delivery_data);
1743 file_put_contents($spool, json_encode($item));
1744 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1749 if ($current_post == 0) {
1750 // This is one of these error messages that never should occur.
1751 logger("couldn't find created item - we better quit now.");
1756 // How much entries have we created?
1757 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1758 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1761 // There are duplicates. We delete our just created entry.
1762 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1764 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1765 DBA::delete('item', ['id' => $current_post]);
1768 } elseif ($entries == 0) {
1769 // This really should never happen since we quit earlier if there were problems.
1770 logger("Something is terribly wrong. We haven't found our created entry.");
1775 logger('created item '.$current_post);
1776 self::updateContact($item);
1778 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1779 $parent_id = $current_post;
1783 self::update(['parent' => $parent_id], ['id' => $current_post]);
1785 $item['id'] = $current_post;
1786 $item['parent'] = $parent_id;
1788 // update the commented timestamp on the parent
1789 // Only update "commented" if it is really a comment
1790 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1791 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1793 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1798 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1799 * We can check for this condition when we decode and encode the stuff again.
1801 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1802 $dsprsig->signature = base64_decode($dsprsig->signature);
1803 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1806 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1807 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1810 if (!empty($diaspora_signed_text)) {
1811 // Formerly we stored the signed text, the signature and the author in different fields.
1812 // We now store the raw data so that we are more flexible.
1813 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1816 $deleted = self::tagDeliver($item['uid'], $current_post);
1819 * current post can be deleted if is for a community page and no mention are
1822 if (!$deleted && !$dontcache) {
1823 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1824 if (DBA::isResult($posted_item)) {
1826 Addon::callHooks('post_local_end', $posted_item);
1828 Addon::callHooks('post_remote_end', $posted_item);
1831 logger('new item not found in DB, id ' . $current_post);
1835 if ($item['parent-uri'] === $item['uri']) {
1836 self::addThread($current_post);
1838 self::updateThread($parent_id);
1841 $delivery_data['iid'] = $current_post;
1843 self::insertDeliveryData($delivery_data);
1848 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1849 * This is not perfect - but a workable solution until we found the reason for the problem.
1851 if (!empty($tags)) {
1852 Term::insertFromTagFieldByItemId($current_post, $tags);
1855 if (!empty($files)) {
1856 Term::insertFromFileFieldByItemId($current_post, $files);
1859 if ($item['parent-uri'] === $item['uri']) {
1860 self::addShadow($current_post);
1862 self::addShadowPost($current_post);
1865 check_user_notification($current_post);
1868 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1869 } elseif (!empty($parent) && $parent['origin']) {
1870 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1873 return $current_post;
1877 * @brief Insert a new item delivery data entry
1879 * @param array $item The item fields that are to be inserted
1881 private static function insertDeliveryData($delivery_data)
1883 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1887 DBA::insert('item-delivery-data', $delivery_data);
1891 * @brief Update an existing item delivery data entry
1893 * @param integer $id The item id that is to be updated
1894 * @param array $item The item fields that are to be inserted
1896 private static function updateDeliveryData($id, $delivery_data)
1898 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1902 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1906 * @brief Insert a new item content entry
1908 * @param array $item The item fields that are to be inserted
1910 private static function insertActivity(&$item)
1912 $activity_index = self::activityToIndex($item['verb']);
1914 if ($activity_index < 0) {
1918 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1919 'uri-hash' => $item['uri-hash'], 'uri-id' => $item['uri-id']];
1921 // We just remove everything that is content
1922 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1923 unset($item[$field]);
1926 // To avoid timing problems, we are using locks.
1927 $locked = Lock::acquire('item_insert_activity');
1929 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1932 // Do we already have this content?
1933 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1934 if (DBA::isResult($item_activity)) {
1935 $item['iaid'] = $item_activity['id'];
1936 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1937 } elseif (DBA::insert('item-activity', $fields)) {
1938 $item['iaid'] = DBA::lastInsertId();
1939 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1941 // This shouldn't happen.
1942 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1943 Lock::release('item_insert_activity');
1947 Lock::release('item_insert_activity');
1953 * @brief Insert a new item content entry
1955 * @param array $item The item fields that are to be inserted
1957 private static function insertContent(&$item)
1959 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash'],
1960 'uri-id' => $item['uri-id']];
1962 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1963 if (isset($item[$field])) {
1964 $fields[$field] = $item[$field];
1965 unset($item[$field]);
1969 // To avoid timing problems, we are using locks.
1970 $locked = Lock::acquire('item_insert_content');
1972 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1975 // Do we already have this content?
1976 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1977 if (DBA::isResult($item_content)) {
1978 $item['icid'] = $item_content['id'];
1979 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1980 } elseif (DBA::insert('item-content', $fields)) {
1981 $item['icid'] = DBA::lastInsertId();
1982 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1984 // This shouldn't happen.
1985 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1988 Lock::release('item_insert_content');
1993 * @brief Update existing item content entries
1995 * @param array $item The item fields that are to be changed
1996 * @param array $condition The condition for finding the item content entries
1998 private static function updateActivity($item, $condition)
2000 if (empty($item['verb'])) {
2003 $activity_index = self::activityToIndex($item['verb']);
2005 if ($activity_index < 0) {
2009 $fields = ['activity' => $activity_index];
2011 logger('Update activity for ' . json_encode($condition));
2013 DBA::update('item-activity', $fields, $condition, true);
2019 * @brief Update existing item content entries
2021 * @param array $item The item fields that are to be changed
2022 * @param array $condition The condition for finding the item content entries
2024 private static function updateContent($item, $condition)
2026 // We have to select only the fields from the "item-content" table
2028 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2029 if (isset($item[$field])) {
2030 $fields[$field] = $item[$field];
2034 if (empty($fields)) {
2035 // when there are no fields at all, just use the condition
2036 // This is to ensure that we always store content.
2037 $fields = $condition;
2040 logger('Update content for ' . json_encode($condition));
2042 DBA::update('item-content', $fields, $condition, true);
2046 * @brief Distributes public items to the receivers
2048 * @param integer $itemid Item ID that should be added
2049 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2051 public static function distribute($itemid, $signed_text = '')
2053 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2054 $parent = self::selectFirst(['owner-id'], $condition);
2055 if (!DBA::isResult($parent)) {
2059 // Only distribute public items from native networks
2060 $condition = ['id' => $itemid, 'uid' => 0,
2061 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2062 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2063 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2064 if (!DBA::isResult($item)) {
2068 $origin = $item['origin'];
2071 unset($item['parent']);
2072 unset($item['mention']);
2073 unset($item['wall']);
2074 unset($item['origin']);
2075 unset($item['starred']);
2079 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2080 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2081 if (!DBA::isResult($owner)) {
2085 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2086 $contacts = DBA::select('contact', ['uid'], $condition);
2087 while ($contact = DBA::fetch($contacts)) {
2088 if ($contact['uid'] == 0) {
2092 $users[$contact['uid']] = $contact['uid'];
2094 DBA::close($contacts);
2096 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2097 $contacts = DBA::select('contact', ['uid'], $condition);
2098 while ($contact = DBA::fetch($contacts)) {
2099 if ($contact['uid'] == 0) {
2103 $users[$contact['uid']] = $contact['uid'];
2105 DBA::close($contacts);
2107 if (!empty($owner['alias'])) {
2108 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2109 $contacts = DBA::select('contact', ['uid'], $condition);
2110 while ($contact = DBA::fetch($contacts)) {
2111 if ($contact['uid'] == 0) {
2115 $users[$contact['uid']] = $contact['uid'];
2117 DBA::close($contacts);
2122 if ($item['uri'] != $item['parent-uri']) {
2123 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2124 while ($parent = self::fetch($parents)) {
2125 $users[$parent['uid']] = $parent['uid'];
2126 if ($parent['origin'] && !$origin) {
2127 $origin_uid = $parent['uid'];
2132 foreach ($users as $uid) {
2133 if ($origin_uid == $uid) {
2134 $item['diaspora_signed_text'] = $signed_text;
2136 self::storeForUser($itemid, $item, $uid);
2141 * @brief Store public items for the receivers
2143 * @param integer $itemid Item ID that should be added
2144 * @param array $item The item entry that will be stored
2145 * @param integer $uid The user that will receive the item entry
2147 private static function storeForUser($itemid, $item, $uid)
2149 $item['uid'] = $uid;
2150 $item['origin'] = 0;
2152 if ($item['uri'] == $item['parent-uri']) {
2153 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2155 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2158 if (empty($item['contact-id'])) {
2159 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2160 if (!DBA::isResult($self)) {
2163 $item['contact-id'] = $self['id'];
2166 /// @todo Handling of "event-id"
2169 if ($item['uri'] == $item['parent-uri']) {
2170 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2171 if (DBA::isResult($contact)) {
2172 $notify = self::isRemoteSelf($contact, $item);
2176 $distributed = self::insert($item, false, $notify, true);
2178 if (!$distributed) {
2179 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2181 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2186 * @brief Add a shadow entry for a given item id that is a thread starter
2188 * We store every public item entry additionally with the user id "0".
2189 * This is used for the community page and for the search.
2190 * It is planned that in the future we will store public item entries only once.
2192 * @param integer $itemid Item ID that should be added
2194 public static function addShadow($itemid)
2196 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2197 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2198 $item = self::selectFirst($fields, $condition);
2200 if (!DBA::isResult($item)) {
2204 // is it already a copy?
2205 if (($itemid == 0) || ($item['uid'] == 0)) {
2209 // Is it a visible public post?
2210 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2214 // is it an entry from a connector? Only add an entry for natively connected networks
2215 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2219 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2223 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2225 if (DBA::isResult($item)) {
2226 // Preparing public shadow (removing user specific data)
2229 unset($item['parent']);
2230 unset($item['wall']);
2231 unset($item['mention']);
2232 unset($item['origin']);
2233 unset($item['starred']);
2234 unset($item['postopts']);
2235 unset($item['inform']);
2236 if ($item['uri'] == $item['parent-uri']) {
2237 $item['contact-id'] = $item['owner-id'];
2239 $item['contact-id'] = $item['author-id'];
2242 $public_shadow = self::insert($item, false, false, true);
2244 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2249 * @brief Add a shadow entry for a given item id that is a comment
2251 * This function does the same like the function above - but for comments
2253 * @param integer $itemid Item ID that should be added
2255 public static function addShadowPost($itemid)
2257 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2258 if (!DBA::isResult($item)) {
2262 // Is it a toplevel post?
2263 if ($item['id'] == $item['parent']) {
2264 self::addShadow($itemid);
2268 // Is this a shadow entry?
2269 if ($item['uid'] == 0) {
2273 // Is there a shadow parent?
2274 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2278 // Is there already a shadow entry?
2279 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2283 // Save "origin" and "parent" state
2284 $origin = $item['origin'];
2285 $parent = $item['parent'];
2287 // Preparing public shadow (removing user specific data)
2290 unset($item['parent']);
2291 unset($item['wall']);
2292 unset($item['mention']);
2293 unset($item['origin']);
2294 unset($item['starred']);
2295 unset($item['postopts']);
2296 unset($item['inform']);
2297 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2299 $public_shadow = self::insert($item, false, false, true);
2301 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2303 // If this was a comment to a Diaspora post we don't get our comment back.
2304 // This means that we have to distribute the comment by ourselves.
2305 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2306 self::distribute($public_shadow);
2311 * Adds a language specification in a "language" element of given $arr.
2312 * Expects "body" element to exist in $arr.
2314 private static function addLanguageToItemArray(&$item)
2316 $naked_body = BBCode::toPlaintext($item['body'], false);
2318 $ld = new Text_LanguageDetect();
2319 $ld->setNameMode(2);
2320 $languages = $ld->detect($naked_body, 3);
2322 if (is_array($languages)) {
2323 $item['language'] = json_encode($languages);
2328 * @brief Creates an unique guid out of a given uri
2330 * @param string $uri uri of an item entry
2331 * @param string $host hostname for the GUID prefix
2332 * @return string unique guid
2334 public static function guidFromUri($uri, $host)
2336 // Our regular guid routine is using this kind of prefix as well
2337 // We have to avoid that different routines could accidentally create the same value
2338 $parsed = parse_url($uri);
2340 // We use a hash of the hostname as prefix for the guid
2341 $guid_prefix = hash("crc32", $host);
2343 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2344 unset($parsed["scheme"]);
2346 // Glue it together to be able to make a hash from it
2347 $host_id = implode("/", $parsed);
2349 // We could use any hash algorithm since it isn't a security issue
2350 $host_hash = hash("ripemd128", $host_id);
2352 return $guid_prefix.$host_hash;
2356 * generate an unique URI
2358 * @param integer $uid User id
2359 * @param string $guid An existing GUID (Otherwise it will be generated)
2363 public static function newURI($uid, $guid = "")
2366 $guid = System::createUUID();
2369 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2373 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2375 * This can be used to filter for inactive contacts.
2376 * Only do this for public postings to avoid privacy problems, since poco data is public.
2377 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2379 * @param array $arr Contains the just posted item record
2381 private static function updateContact($arr)
2383 // Unarchive the author
2384 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2385 if (DBA::isResult($contact)) {
2386 Contact::unmarkForArchival($contact);
2389 // Unarchive the contact if it's not our own contact
2390 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2391 if (DBA::isResult($contact)) {
2392 Contact::unmarkForArchival($contact);
2395 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2397 // Is it a forum? Then we don't care about the rules from above
2398 if (!$update && ($arr["network"] == Protocol::DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2399 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2405 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2406 ['id' => $arr['contact-id']]);
2408 // Now do the same for the system wide contacts with uid=0
2409 if (!$arr['private']) {
2410 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2411 ['id' => $arr['owner-id']]);
2413 if ($arr['owner-id'] != $arr['author-id']) {
2414 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2415 ['id' => $arr['author-id']]);
2420 public static function setHashtags(&$item)
2423 $tags = get_tags($item["body"]);
2426 if (!count($tags)) {
2430 // This sorting is important when there are hashtags that are part of other hashtags
2431 // Otherwise there could be problems with hashtags like #test and #test2
2434 $URLSearchString = "^\[\]";
2436 // All hashtags should point to the home server if "local_tags" is activated
2437 if (Config::get('system', 'local_tags')) {
2438 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2439 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2441 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2442 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2445 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2446 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2448 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2451 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2453 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2456 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2458 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2461 // Repair recursive urls
2462 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2463 "#$2", $item["body"]);
2465 foreach ($tags as $tag) {
2466 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2470 $basetag = str_replace('_',' ',substr($tag,1));
2472 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2474 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2476 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2477 if (strlen($item["tag"])) {
2478 $item["tag"] = ','.$item["tag"];
2480 $item["tag"] = $newtag.$item["tag"];
2484 // Convert back the masked hashtags
2485 $item["body"] = str_replace("#", "#", $item["body"]);
2488 public static function getGuidById($id)
2490 $item = self::selectFirst(['guid'], ['id' => $id]);
2491 if (DBA::isResult($item)) {
2492 return $item['guid'];
2499 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2500 * @param string $guid item guid
2501 * @param int $uid user id
2502 * @return array with id and nick of the item with the given guid
2504 public static function getIdAndNickByGuid($guid, $uid = 0)
2510 $uid == local_user();
2513 // Does the given user have this item?
2515 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2516 if (DBA::isResult($item)) {
2517 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2518 if (!DBA::isResult($user)) {
2522 $nick = $user['nickname'];
2526 // Or is it anywhere on the server?
2528 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2529 $item = self::selectFirst(['id', 'uid'], $condition);
2530 if (DBA::isResult($item)) {
2531 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2532 if (!DBA::isResult($user)) {
2536 $nick = $user['nickname'];
2539 return ["nick" => $nick, "id" => $id];
2543 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2545 * @param int $item_id
2546 * @return bool true if item was deleted, else false
2548 private static function tagDeliver($uid, $item_id)
2552 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2553 if (!DBA::isResult($user)) {
2557 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2558 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2560 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2561 if (!DBA::isResult($item)) {
2565 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2568 * Diaspora uses their own hardwired link URL in @-tags
2569 * instead of the one we supply with webfinger
2571 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2573 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2575 foreach ($matches as $mtch) {
2576 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2578 logger('mention found: ' . $mtch[2]);
2584 if (($community_page || $prvgroup) &&
2585 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2586 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2588 logger("no-mention top-level post to community or private group. delete.");
2589 DBA::delete('item', ['id' => $item_id]);
2595 $arr = ['item' => $item, 'user' => $user];
2597 Addon::callHooks('tagged', $arr);
2599 if (!$community_page && !$prvgroup) {
2604 * tgroup delivery - setup a second delivery chain
2605 * prevent delivery looping - only proceed
2606 * if the message originated elsewhere and is a top-level post
2608 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2612 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2613 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2614 if (!DBA::isResult($self)) {
2618 $owner_id = Contact::getIdForURL($self['url']);
2620 // also reset all the privacy bits to the forum default permissions
2622 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2624 $psid = PermissionSet::fetchIDForPost($user);
2626 $forum_mode = ($prvgroup ? 2 : 1);
2628 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2629 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2630 self::update($fields, ['id' => $item_id]);
2632 self::updateThread($item_id);
2634 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2637 public static function isRemoteSelf($contact, &$datarray)
2641 if (!$contact['remote_self']) {
2645 // Prevent the forwarding of posts that are forwarded
2646 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2647 logger('Already forwarded', LOGGER_DEBUG);
2651 // Prevent to forward already forwarded posts
2652 if ($datarray["app"] == $a->getHostName()) {
2653 logger('Already forwarded (second test)', LOGGER_DEBUG);
2657 // Only forward posts
2658 if ($datarray["verb"] != ACTIVITY_POST) {
2659 logger('No post', LOGGER_DEBUG);
2663 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2664 logger('Not public', LOGGER_DEBUG);
2668 $datarray2 = $datarray;
2669 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2670 if ($contact['remote_self'] == 2) {
2671 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2672 ['uid' => $contact['uid'], 'self' => true]);
2673 if (DBA::isResult($self)) {
2674 $datarray['contact-id'] = $self["id"];
2676 $datarray['owner-name'] = $self["name"];
2677 $datarray['owner-link'] = $self["url"];
2678 $datarray['owner-avatar'] = $self["thumb"];
2680 $datarray['author-name'] = $datarray['owner-name'];
2681 $datarray['author-link'] = $datarray['owner-link'];
2682 $datarray['author-avatar'] = $datarray['owner-avatar'];
2684 unset($datarray['created']);
2685 unset($datarray['edited']);
2687 unset($datarray['network']);
2688 unset($datarray['owner-id']);
2689 unset($datarray['author-id']);
2692 if ($contact['network'] != Protocol::FEED) {
2693 $datarray["guid"] = System::createUUID();
2694 unset($datarray["plink"]);
2695 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2696 $datarray["parent-uri"] = $datarray["uri"];
2697 $datarray["thr-parent"] = $datarray["uri"];
2698 $datarray["extid"] = Protocol::DFRN;
2699 $urlpart = parse_url($datarray2['author-link']);
2700 $datarray["app"] = $urlpart["host"];
2702 $datarray['private'] = 0;
2706 if ($contact['network'] != Protocol::FEED) {
2707 // Store the original post
2708 $result = self::insert($datarray2, false, false);
2709 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2711 $datarray["app"] = "Feed";
2715 // Trigger automatic reactions for addons
2716 $datarray['api_source'] = true;
2718 // We have to tell the hooks who we are - this really should be improved
2719 $_SESSION["authenticated"] = true;
2720 $_SESSION["uid"] = $contact['uid'];
2729 * @param array $item
2733 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2735 if (Config::get('system', 'disable_embedded')) {
2739 logger('check for photos', LOGGER_DEBUG);
2740 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2745 $img_start = strpos($orig_body, '[img');
2746 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2747 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2749 while (($img_st_close !== false) && ($img_len !== false)) {
2750 $img_st_close++; // make it point to AFTER the closing bracket
2751 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2753 logger('found photo ' . $image, LOGGER_DEBUG);
2755 if (stristr($image, $site . '/photo/')) {
2756 // Only embed locally hosted photos
2758 $i = basename($image);
2759 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2760 $x = strpos($i, '-');
2763 $res = substr($i, $x + 1);
2764 $i = substr($i, 0, $x);
2765 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2766 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2767 if (DBA::isResult($photo)) {
2769 * Check to see if we should replace this photo link with an embedded image
2770 * 1. No need to do so if the photo is public
2771 * 2. If there's a contact-id provided, see if they're in the access list
2772 * for the photo. If so, embed it.
2773 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2774 * permissions, regardless of order but first check to see if they're an exact
2775 * match to save some processing overhead.
2777 if (self::hasPermissions($photo)) {
2779 $recips = self::enumeratePermissions($photo);
2780 if (in_array($cid, $recips)) {
2784 if (self::samePermissions($item, $photo)) {
2790 $data = $photo['data'];
2791 $type = $photo['type'];
2793 // If a custom width and height were specified, apply before embedding
2794 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2795 logger('scaling photo', LOGGER_DEBUG);
2797 $width = intval($match[1]);
2798 $height = intval($match[2]);
2800 $Image = new Image($data, $type);
2801 if ($Image->isValid()) {
2802 $Image->scaleDown(max($width, $height));
2803 $data = $Image->asString();
2804 $type = $Image->getType();
2808 logger('replacing photo', LOGGER_DEBUG);
2809 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2810 logger('replaced: ' . $image, LOGGER_DATA);
2816 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2817 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2818 if ($orig_body === false) {
2822 $img_start = strpos($orig_body, '[img');
2823 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2824 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2827 $new_body = $new_body . $orig_body;
2832 private static function hasPermissions($obj)
2834 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2835 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2838 private static function samePermissions($obj1, $obj2)
2840 // first part is easy. Check that these are exactly the same.
2841 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2842 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2843 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2844 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2848 // This is harder. Parse all the permissions and compare the resulting set.
2849 $recipients1 = self::enumeratePermissions($obj1);
2850 $recipients2 = self::enumeratePermissions($obj2);
2854 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2855 return ($recipients1 == $recipients2);
2858 // returns an array of contact-ids that are allowed to see this object
2859 public static function enumeratePermissions($obj)
2861 $allow_people = expand_acl($obj['allow_cid']);
2862 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2863 $deny_people = expand_acl($obj['deny_cid']);
2864 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2865 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2866 $deny = array_unique(array_merge($deny_people, $deny_groups));
2867 $recipients = array_diff($recipients, $deny);
2871 public static function getFeedTags($item)
2875 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2877 for ($x = 0; $x < $cnt; $x ++) {
2878 if ($matches[1][$x]) {
2879 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2884 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2886 for ($x = 0; $x < $cnt; $x ++) {
2887 if ($matches[1][$x]) {
2888 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2895 public static function expire($uid, $days, $network = "", $force = false)
2897 if (!$uid || ($days < 1)) {
2901 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2902 $uid, GRAVITY_PARENT];
2905 * $expire_network_only = save your own wall posts
2906 * and just expire conversations started by others
2908 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2910 if ($expire_network_only) {
2911 $condition[0] .= " AND NOT `wall`";
2914 if ($network != "") {
2915 $condition[0] .= " AND `network` = ?";
2916 $condition[] = $network;
2919 * There is an index "uid_network_received" but not "uid_network_created"
2920 * This avoids the creation of another index just for one purpose.
2921 * And it doesn't really matter wether to look at "received" or "created"
2923 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2924 $condition[] = $days;
2926 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2927 $condition[] = $days;
2930 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2932 if (!DBA::isResult($items)) {
2936 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2938 // Forcing expiring of items - but not notes and marked items
2940 $expire_items = true;
2943 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2944 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2945 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2949 while ($item = Item::fetch($items)) {
2950 // don't expire filed items
2952 if (strpos($item['file'], '[') !== false) {
2956 // Only expire posts, not photos and photo comments
2958 if (!$expire_photos && strlen($item['resource-id'])) {
2960 } elseif (!$expire_starred && intval($item['starred'])) {
2962 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2964 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2968 self::deleteById($item['id'], PRIORITY_LOW);
2973 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2976 public static function firstPostDate($uid, $wall = false)
2978 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2979 $params = ['order' => ['created' => false]];
2980 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2981 if (DBA::isResult($thread)) {
2982 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2988 * @brief add/remove activity to an item
2990 * Toggle activities as like,dislike,attend of an item
2992 * @param string $item_id
2993 * @param string $verb
2994 * Activity verb. One of
2995 * like, unlike, dislike, undislike, attendyes, unattendyes,
2996 * attendno, unattendno, attendmaybe, unattendmaybe
2997 * @hook 'post_local_end'
2999 * 'post_id' => ID of posted item
3001 public static function performLike($item_id, $verb)
3003 if (!local_user() && !remote_user()) {
3010 $activity = ACTIVITY_LIKE;
3014 $activity = ACTIVITY_DISLIKE;
3018 $activity = ACTIVITY_ATTEND;
3022 $activity = ACTIVITY_ATTENDNO;
3025 case 'unattendmaybe':
3026 $activity = ACTIVITY_ATTENDMAYBE;
3029 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
3033 // Enable activity toggling instead of on/off
3034 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3036 logger('like: verb ' . $verb . ' item ' . $item_id);
3038 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3039 if (!DBA::isResult($item)) {
3040 logger('like: unknown item ' . $item_id);
3044 $item_uri = $item['uri'];
3046 $uid = $item['uid'];
3047 if (($uid == 0) && local_user()) {
3048 $uid = local_user();
3051 if (!can_write_wall($uid)) {
3052 logger('like: unable to write on wall ' . $uid);
3056 // Retrieves the local post owner
3057 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3058 if (!DBA::isResult($owner_self_contact)) {
3059 logger('like: unknown owner ' . $uid);
3063 // Retrieve the current logged in user's public contact
3064 $author_id = public_contact();
3066 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3067 if (!DBA::isResult($author_contact)) {
3068 logger('like: unknown author ' . $author_id);
3072 // Contact-id is the uid-dependant author contact
3073 if (local_user() == $uid) {
3074 $item_contact_id = $owner_self_contact['id'];
3075 $item_contact = $owner_self_contact;
3077 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3078 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3079 if (!DBA::isResult($item_contact)) {
3080 logger('like: unknown item contact ' . $item_contact_id);
3085 // Look for an existing verb row
3086 // event participation are essentially radio toggles. If you make a subsequent choice,
3087 // we need to eradicate your first choice.
3088 if ($event_verb_flag) {
3089 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3091 // Translate to the index based activity index
3093 foreach ($verbs as $verb) {
3094 $activities[] = self::activityToIndex($verb);
3097 $activities = self::activityToIndex($activity);
3100 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3101 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3103 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3105 // If it exists, mark it as deleted
3106 if (DBA::isResult($like_item)) {
3107 self::deleteById($like_item['id']);
3109 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3114 // Verb is "un-something", just trying to delete existing entries
3115 if (strpos($verb, 'un') === 0) {
3119 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3122 'guid' => System::createUUID(),
3123 'uri' => self::newURI($item['uid']),
3124 'uid' => $item['uid'],
3125 'contact-id' => $item_contact_id,
3126 'wall' => $item['wall'],
3128 'network' => Protocol::DFRN,
3129 'gravity' => GRAVITY_ACTIVITY,
3130 'parent' => $item['id'],
3131 'parent-uri' => $item['uri'],
3132 'thr-parent' => $item['uri'],
3133 'owner-id' => $author_id,
3134 'author-id' => $author_id,
3135 'body' => $activity,
3136 'verb' => $activity,
3137 'object-type' => $objtype,
3138 'allow_cid' => $item['allow_cid'],
3139 'allow_gid' => $item['allow_gid'],
3140 'deny_cid' => $item['deny_cid'],
3141 'deny_gid' => $item['deny_gid'],
3146 $new_item_id = self::insert($new_item);
3148 // If the parent item isn't visible then set it to visible
3149 if (!$item['visible']) {
3150 self::update(['visible' => true], ['id' => $item['id']]);
3153 // Save the author information for the like in case we need to relay to Diaspora
3154 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3156 $new_item['id'] = $new_item_id;
3158 Addon::callHooks('post_local_end', $new_item);
3160 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3165 private static function addThread($itemid, $onlyshadow = false)
3167 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3168 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3169 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3170 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3171 $item = self::selectFirst($fields, $condition);
3173 if (!DBA::isResult($item)) {
3177 $item['iid'] = $itemid;
3180 $result = DBA::insert('thread', $item);
3182 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3186 private static function updateThread($itemid, $setmention = false)
3188 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3189 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3190 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3191 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3193 $item = self::selectFirst($fields, $condition);
3194 if (!DBA::isResult($item)) {
3199 $item["mention"] = 1;
3206 foreach ($item as $field => $data) {
3207 if (!in_array($field, ["guid"])) {
3208 $fields[$field] = $data;
3212 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3214 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3217 private static function deleteThread($itemid, $itemuri = "")
3219 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3220 if (!DBA::isResult($item)) {
3221 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3225 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3227 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3229 if ($itemuri != "") {
3230 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3231 if (!self::exists($condition)) {
3232 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3233 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);